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与数据持久层框架的整合我们就介绍到这了 四不四很简单~~~

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值