【Spring Boot 系列 持久层开发】

1、数据源配置

1.1、添加POM依赖
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <scope>runtime</scope>
</dependency>
1.2、数据源的默认配置

由于只添加了spring-boot-starter-jdbcpom依赖所以默认使用的是org.apache.tomcat.jdbc.pool.DataSource数据源, 数据源属性的相关配置在org.springframework.boot.autoconfigure.jdbc.DataSourceProperties里面。

2、集成JPA

2.1、编写实体类
@Entity
@Table(name = "tb_user")
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler"})
public class User {
    @Id
    @GeneratedValue
    private Integer id;

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

    @Column
    private String email;

  //省略getter/setter方法
}

说明:编写实体类和数据表进行映射,配置好表字段和实体属性的映射关系

  • 使用@Entity告诉JPA这是一个实体类
  • 使用@Table指定和哪个数据表对应,如果省略默认表名就是类名小写
  • 使用@Id指定该属性对应于表的主键,使用@GeneratedValue指定主键的生成方式
  • 使用@Cloumn指定该属性对应于表的具体字段,默认情况下属性名就是字段名

注意:如果未使用@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler"})将会出现以下错误

"Could not write JSON: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.hanson.entity.User_$$_jvstf1d_0[\"handler\"])"

出现错误的原因:

hibernate延时加载因为jsonplugin用的是Java的内审机制.hibernate会给被管理的pojo加入一个hibernateLazyInitializer属性,jsonplugin会把hibernateLazyInitializer也拿出来操作,并读取里面一个不能被反射操作的属性就产生了这个异常. 
2.2、编写Dao接口
public interface UserRepository extends JpaRepository<User,Integer>{
}

JpaRepository封装了对数据库(表)的简单操作

2.3、JPA的配置
spring:
# 数据源基本属性配置
  datasource:
    url: jdbc:mysql://localhost:3306/jpa
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
# jpa基本配置
  jpa:
    hibernate:
#     创建或更新表
      ddl-auto: update
#   控制台显示SQL
    show-sql: true

3、集成MyBatis

3.1、添加MyBatis依赖
<dependency>
  	<groupId>org.mybatis.spring.boot</groupId>
  	<artifactId>mybatis-spring-boot-starter</artifactId>
  	<version>1.3.2</version>
</dependency>

该依赖引入了mybatismybatis-spring整合包、mybatis-spring-boot-autoconfigure

3.2、数据源配置
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/springboot
    driver-class-name: com.mysql.jdbc.Driver
# 打印sql
logging:
  level:
     com.hanson.mapper : debug
3.3、创建表
--用户表
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL COMMENT '用户名称',
  `birthday` date DEFAULT NULL COMMENT '生日',
  `sex` char(1) DEFAULT NULL COMMENT '性别',
  `address` varchar(256) DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;
--订单表
DROP TABLE IF EXISTS `orders`;
CREATE TABLE `orders` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL COMMENT '下单用户id',
  `number` varchar(32) NOT NULL COMMENT '订单号',
  `createtime` datetime NOT NULL COMMENT '创建订单时间',
  `note` varchar(100) DEFAULT NULL COMMENT '备注',
  PRIMARY KEY (`id`),
  KEY `FK_orders_1` (`user_id`),
  CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
3.3、创建实体类
public class User {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
  //省略getter/setter方法
}

public class Order {
    private Integer id;
    private Integer userId;
    private String number;
    private Date createTime;
    private String note;
  //省略getter/setter方法
}
3.4、基于注解开发
3.4.1、Mapper接口
@Mapper
public interface OrderMapper {

    @Select("SELECT * from orders where id = #{id}")
    Order getOrderById(Integer id);

    @Delete("DELETE FROM orders where id  = #{id}")
    int delOrderById(Integer id);

    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into orders(user_id,number,createtime,note)values(#{userId},#{number},#{createTime},#{note})")
    int add(Order order);

    @Update("update orders set user_id = #{userId}, number=#{number},note=#{note} where id=#{id}")
    int update(Order order);
}

使用@Mapper表明这是一个映射器,映射器需要被MyBatis管理。 当接口有很多在每一个Mapper接口上添加@Mapper也很麻烦,所以需要用到一个Mapper接口扫描器@MapperScan

3.4.2、Mapper接口扫描器
@SpringBootApplication
@MapperScan({"com.hanson.mapper"})
public class MybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }
}
3.5、基于XML开发
3.5.1、Mapper接口
public interface UserMapper {
    User getUserById(Integer id);
    int updateUser(User user);
}

Mapper接口依然需要被Mybatis管理所以要么是使用@Mapper注解要么使用Mapper接口扫描器@MapperScan

3.5.2、Mapper.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.hanson.mapper.UserMapper">
    <select id="getUserById" resultType="com.hanson.bean.User">
        SELECT *
        FROM user
        WHERE id = #{id}
    </select>
    <update id="updateUser">
        UPDATE user
        SET username = #{username},
            birthday = #{birthday},
            sex      = #{sex},
            address  = #{address}
        WHERE
            id = #{id}
    </update>
</mapper>
3.5.3、MyBatis核心配置文件
<?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>
</configuration>
3.5.4、配置MyBatis
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/springboot
    driver-class-name: com.mysql.jdbc.Driver
# 打印sql
logging:
  level:
     com.hanson.mapper : debug
mybatis:
#  mybatis全局配置
  config-location: classpath:mybatis/mybatisConfig.xml
#  配置mapper接口映射文件
  mapper-locations: classpath:mybatis/mapper/*.xml
3.6、MyBatis定制
3.6.1、基于XML定制

在mybtais的核心配置文件中自定义配置自定义内容,可以配置Mybatis的运行行为

3.6.2、基于配置文件定制

参考MyBatis的属性配置类在application.properties或者aplication.yml配置

3.6.3、基于Java代码定制
@SpringBootConfiguration
public class MybatisConfiguration {
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return (configuration) -> {
            //别名注册器
            TypeAliasRegistry typeAliasRegistry = configuration.getTypeAliasRegistry();
            //mapper接口注册器
            MapperRegistry mapperRegistry = configuration.getMapperRegistry();
            //类型处理器
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            //...
        };
    }
}

推荐第二种或者第三种

转载于:https://my.oschina.net/serve/blog/1922792

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值