SpingBoot與數據訪問(二)整合Mybatis與JPA

之前我們說了springBoot 整合JDBC的方式以及說了切換爲Druid數據源,我們這篇博客說一下springBoot與Mybatis的整合

1. 首先加入Mybatis以及相關依賴

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version>
		</dependency>

		<!-- 數據庫連接池  -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.25</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
</dependencies>

1.1. Mybatis XML方式

我們首先說一下xml配置文件的整合
整個項目結構如下
在這裏插入圖片描述
之前說的一些連接配置以及Druid數據源的配置這裏就不再重複展示了,相關可以查看上一篇博客。
我們首先在配置文件中指定我們Mybatis配置文件以及Mapper位置

## Mybatis 配置
mybatis.mapperLocations=classpath:mybatis/mapper/*.xml
mybatis.configLocation=classpath:mybatis/mybatis-conf.xml

接下里看一下我們的StudentMapper.xml

注意這裏與SpringMVC有幾點不同

  • SpringMVC中xml的nameSpace只要唯一就可以了 在Dao接口的實現類中通過sqlSessionTemplate.XXX("namespace.methodName")就ok了
  • 而我們springBoot不需要寫Dao實現類 只要一個接口就ok了,並且接口中方法名要與xml方法名一致而且xml的namespace爲接口全類名

SpringMVC

public class StudentDaoImpl implements StudentDao {

    private SqlSessionTemplate sqlSessionTemplate;

    public void setSqlSession(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSessionTemplate = sqlSessionTemplate;
    }

    @Override
    public List<Student> queryStudentList() {
        return sqlSessionTemplate.selectList("Student.queryStudentList");
    }

}
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="Student">
    <resultMap type="com.mapc.bean.Student" id="studentResultMapper">
        <id column="ID" jdbcType="VARCHAR" property="id"/>
        <result column="NAME" jdbcType="VARCHAR" property="name"/>
        <result column="AGE" jdbcType="INTEGER" property="age"/>
    </resultMap>
    <select id="queryStudentList" resultMap="studentResultMapper">
        select ID,NAME,AGE from STUDENT 
    </select>
</mapper>

SpringBoot

mybatis-conf.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
//開啓駝峯
<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

StudentMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.demo.dao.StudentDao" >

    <resultMap id="StudentResultMap" type="com.example.demo.model.Student">
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="student_name" property="studentName" jdbcType="VARCHAR"/>
        <result column="student_score" property="studentScore" jdbcType="REAL"/>
    </resultMap>

    <select id="getAll" resultMap="StudentResultMap">
      SELECT * FROM student
    </select>

    <select id="findOne" resultMap="StudentResultMap" parameterType="java.lang.Integer">
        SELECT * FROM student where id = #{id}
    </select>

    <insert id="save" parameterType="com.example.demo.model.Student">
        insert into student (student_name,student_score) values (#{studentName},#{studentScore});
    </insert>

    <delete id="delete" parameterType="java.lang.Integer">
        DELETE FROM student WHERE id = #{id}
    </delete>

    <update id="update" parameterType="com.example.demo.model.Student">
        UPDATE student SET student_name =#{studentName},student_score=#{studentScore} WHERE id = #{id}
    </update>
</mapper>

創建StudentDao 接口(名字要與xml對應)

public interface StudentDao {

    public List<Student> getAll();

    public Student findOne(Integer id);

    public void save(Student student);

    public void delete(Integer id);

    public void update(Student student);
}

接下來我們寫測試用例進行測試

@Test
	public void add() throws SQLException {

		Student student = new Student();
		student.setStudentName("yz");
		student.setStudentScore(100);
		studentDao.save(student);
	}

在這裏插入圖片描述
可以看到已經添加成功了,我們再測試一個查詢

@Test
	public void getById() throws SQLException {
		System.out.println(studentDao.findOne(1));
	}

在這裏插入圖片描述

1.2. Mybatis 註解方式

配置文件有時候顯得過於麻煩,那我們就使用註解實現Mybatis
首先我們去掉XML相關配置 也就是


## Mybatis 配置
mybatis.mapperLocations=classpath:mybatis/mapper/*.xml
mybatis.configLocation=classpath:mybatis/mybatis-conf.xml

以及指定的XML文件

接下來我們創建EmbDao 接口

public interface EmbDao {

    @Select("select * from emb_t_dictBusType")
    public List<Emc> query();

    @Select("select * from emb_t_dictBusType where emb_c_busTypeID = #{id}")
    public Emc getById(Integer id);

    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into emb_t_dictBusType (emb_c_busTypeEnName,emb_c_busTypeZhName) values(#{embCBusTypeEnName},#{embCBusTypeZhName})")
    public void insert(Emc emc);

    @Update("update emb_t_dictBusType set emb_c_busTypeEnName =#{embCBusTypeEnName} where emb_c_busTypeID = #{embCBusTypeId}")
    public void update(Emc emc);

}

最後我們需要加上MapperScan 註解 ,指定掃描的mapper所在包

@MapperScan(basePackages="com.example.demo.dao")
@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
}

我們編寫測試用例進行測試

@Test
	public void add() throws SQLException {
		Emc emc = new Emc();
		emc.setEmbCBusTypeZhName("zh");
		emc.setEmbCBusTypeEnName("en");
		embDao.insert(emc);

	}	

在這裏插入圖片描述

@Test
	public void update() throws SQLException {
		Emc emc = new Emc();
		emc.setEmbCBusTypeZhName("zh");
		emc.setEmbCBusTypeId(1);
		emc.setEmbCBusTypeEnName("lalala");
		embDao.update(emc);

	}

在這裏插入圖片描述

@Test
	public void getById() throws SQLException {
		Emc emc = embDao.getById(1);
		System.out.println(emc);
	}

在這裏插入圖片描述
發現查詢結果爲null,是因爲我們數據庫字段與model字段名稱不一致而沒有映射成功。
我們需要開啓駝峯配置實現數據庫字段與model映射(xml 不需要 resultMap已經指定)

@Configuration
public class MyBatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

在這裏插入圖片描述

2. 整合JPA

2.1 SpringData簡介

在這裏插入圖片描述

  1. SpringData:Spring 的一個子項目。用於簡化數據庫訪問,支持NoSQL 和 關係數據存儲。其主要目標是使數據庫的訪問變得方便快捷。
  2. JPA Spring Data:致力於減少數據訪問層 (DAO) 的開發量. 開發者唯一要做的,就只是聲明持久層的接口,其他都交給 Spring Data JPA 來完成!

2.2 整合SpringData JPA

2.2.1 加入相關依賴

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<!-- 數據庫連接池  -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.25</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
	</dependencies>

2.2.2 編寫實體類

@Entity(name="tbl_user")
public class User {

    @Id
    @GeneratedValue
    private Integer id;

    @Column(name="first_name")
    private String firstName;

    @Column(name="last_name")
    private String lastName;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}
  1. 我們可以使用@Entity@Table 註解 聲明我們model與表名的對應關係,如果不寫@Table 註解
    自動使用@Entity name屬性
  2. @Column(name="last_name") 加在get方法上 或者 字段上 自動對應數據庫字段與model 字段
  3. 使用@Id@GeneratedValue 註解 定義表的主鍵與主鍵生成策略

這樣在項目啓動的時候就會爲我們自動創建表,並映射對象與表關係

我們需要在配置文件中加上spring.jpa.hibernate.ddl-auto=update ,這樣我們以後每次啓動項目就不會重新創建表,如果有更改就只會更新我們的列相關屬性,至於ddl-auto的其他值 這裏就不多說了,有興趣的自行百度。其實和Hibernate 是一樣的,因爲Hibernate 也是JPA 的一種實現

2.2.3 編寫Dao

public interface UserDao extends JpaRepository<User,Integer>{

}

我們只要編寫一個接口去繼承JpaRepository 增刪改查就OK了,傳入兩個泛型,一個是操作的Model,一個是主鍵的類型
,可能你會想我們沒有任何實現怎麼就可以了呢,我們來看一下繼承關係

在這裏插入圖片描述

可以看到JpaRepository 繼承了 PagingAndSortingRepositoryQueryByExampleExecutor 以及CrudRepository
所以我們UserDao就有了增刪改查 以及分頁相關方法。這也就是Spring實現簡化開發的一個思路

當我們啓動項目的時候,發現已經爲我們自動創建了表
在這裏插入圖片描述
編寫測試用例

@Test
	public void add() {
		User user = new User();
		user.setFirstName("yang");
		user.setLastName("zhao");
		userDao.save(user);
	}

在這裏插入圖片描述

@Test
	public void del() {
		userDao.delete(1);
	}

在這裏插入圖片描述
springBoot與數據持久層框架的整合我們就介紹到這了 四不四很簡單~~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章