hibernate及SpringBoot集成Jpa实现对数据库操作

首先使用Maven工程和junit完成hibernate对数据库的简单操作,完成之后在使用SpringBoot集成Jap完成hibernate对数据库的操作。本文仅供新手学习查看,具体线上使用需要对代码继续进行相关优化。

1、先创建一个Maven工程,导入相关依赖。

 <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
        </dependency>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>
        <!--单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!--hibernate-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.6.14.Final</version>
        </dependency>

2、在resources目录下创建hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!--数据库配置-->
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/user-mode</property>
        <property name="connection.username">root</property>
        <property name="connection.password">1234qwer</property>
        <!-- Hibernate 方言 -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- 打印 SQL 语句-->
        <property name="show_sql">true</property>
        <!-- 格式化 SQL 语句-->
        <property name="format_sql">true</property>
        <!-- 映射文件所在位置 -->
        <mapping resource="/mapper/User.hbm.xml" />
    </session-factory>
</hibernate-configuration>

3、创建一个实体类

@Datapublic class User {private Long id;
    private String name;
    private String password;
    private String account;
    private String email;private String secondName;
}

4、在resources目录下创建一个mapper目录,在mapper目录下面创建User实体类的映射文件User.hbm.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <!-- name 属性:持久化类的全路径 -->
    <!-- table 属性:表的名称 -->
    <class name="com.itmy.entity.User" table="tb_user">
        <id name="id" column="id" type="java.lang.Long">
            <!--主键生成策略-->
            <generator class="native"></generator>
        </id>
        <property name="name" column="name" type="java.lang.String" not-null="false" length="50"></property>
        <property name="account" column="account" type="java.lang.String"></property>
        <property name="email" column="email" type="java.lang.String"></property>
        <property name="password" column="password" type="java.lang.String"></property>
        <property name="secondName" column="second_name" type="java.lang.String"></property>
    </class>
</hibernate-mapping>

配置完上述配置之后,接下来我们就可以使用junit进行测试了,先在test目录下面创建一个测试类UserTest。

5、使用junit添加一个User用户

 @org.junit.Test
    public void TestSave(){
        //读取 hibernate.cfg.xml配置文件, 创建会话工厂 SessionFactory
        Configuration configuration = new Configuration().configure();
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        // 获取 Session 对象
        Session openSession = sessionFactory.openSession();
        //开启事务
        openSession.beginTransaction();
        User user = new User();
        user.setAccount("hibernateTest01");
        user.setName("hibernateTest01");
        user.setPassword("ASWDEWSA");
        user.setEmail("hibernate02@hbm.com");
        user.setSecondName("hibernateTest01");
        openSession.save(user);
        //提交事务
        openSession.getTransaction().commit();
    }

执行之后,控制台没有报红,说明添加成功了。可以给上述代码做下优化,帮助我们更方便的完成其他操作。

    private Session openSession;
    @Before
    public void before(){
        //读取 hibernate.cfg.xml配置文件, 创建会话工厂 SessionFactory
        Configuration configuration = new Configuration().configure();
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        // 获取 Session 对象
        openSession = sessionFactory.openSession();
    }

    @org.junit.Test
    public void TestSave(){
//        //读取 hibernate.cfg.xml配置文件, 创建会话工厂 SessionFactory
  //      Configuration configuration = new Configuration().configure();
 //       SessionFactory sessionFactory = configuration.buildSessionFactory();
//        // 获取 Session 对象
 //       Session openSession = sessionFactory.openSession();
        //开启事务
        openSession.beginTransaction();
        User user = new User();
        user.setAccount("hibernateTest01");
        user.setName("hibernateTest01");
        user.setPassword("ASWDEWSA");
        user.setEmail("hibernate02@hbm.com");
        user.setSecondName("hibernateTest01");
        openSession.save(user);
        //提交事务
        openSession.getTransaction().commit();
    }
   @After
public void after(){
if (openSession != null){
openSession.close();
}
}

实现更新、删除、查询,查询有许多种方法,后面可以进行深入学习。

 @org.junit.Test
    public void testUpdate(){
        //开启事务
        openSession.beginTransaction();
        User user = new User();
        user.setId(8L);
        user.setAccount("hibernateTest03");
        user.setName("hibernateTest03");
        user.setPassword("ASWDEWSAW");
        user.setEmail("hibernate03@hbm.com");
        user.setSecondName("hibernateTest03");
        openSession.update(user);
        //提交事务
        openSession.getTransaction().commit();
    }
    @org.junit.Test
    public void testDelete(){
        //开启事务
        openSession.beginTransaction();
        User user = new User();
        user.setId(8L);
        openSession.delete(user);
        //提交事务
        openSession.getTransaction().commit();
    }
    @org.junit.Test
    public void testFind(){
        User user = new User();
        user.setId(8L);
        //已过时
        Criteria criteria = openSession.createCriteria(User.class);
        List list = criteria.list();
        for (Object o : list) {
            System.out.println(o);
        }
        List fromUser = openSession.createQuery("from User").list();
        fromUser.forEach(System.out::println);
    }

到这里通过maven简单的使用hibernate的操作就完成了,后面我们使用SpringBoot集成Jpa。

6、首先调整我们的maven项目,添加springboot相关依赖以及jpa依赖。

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.11.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!--数据库连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.16</version>
        </dependency>
 <dependencies>

7、创建Springboot启动类

/**
 * @date: 2023-05-11 13:29
 */
@SpringBootApplication
public class HibernApplication {

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

8、在resources目录下创建yml文件

server:
  port: 8800
spring:
  application:
    name: hibernate
  profiles:
    active: prod
spring:
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQLDialect
        new_generator_mappings: false
        format_sql: true
        #show_sql: true
    database: mysql
    show-sql: true
    #当数据库表没有该属性字段,会根据实体类相关字段自动创建一个字段,如secondName在数据库创建的为second_name
    hibernate:
      ddl-auto: update
   # 生产环境设置成 none,避免程序运行时自动更新数据库结构
#ddl-auto: none
  datasource:
   driver-class-name: com.mysql.cj.jdbc.Driver
   type: com.alibaba.druid.pool.DruidDataSource
   url: jdbc:mysql://localhost:3306/user-mode?serverTimezone=Asia/Shanghai
   username: root
   password: 1234qwer

9、调整之前创建的实体类

@Data
@Entity
@Table(name = "tb_user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id",nullable = false)
    private Long id;

    private String name;

    private String password;

    private String account;

    private String email;

    @Column(name = "second_name",nullable = false)
    private String secondName;

}

10、创建一个dao层接口继承jpa接口

public interface UserMapper extends JpaRepository<User,Long> {
   
}

后面就跟正常调用方法一样,通过注入UserMapp接口,进行调用。

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {
        List<User> userIterable = userMapper.findAll();
        return userIterable;
    }
    @Override
    public User save() {
        User user = new User();
        user.setAccount("hibernateJPa03");
        user.setName("hibernateJPa03");
        user.setPassword("ASWDEWSAW");
        user.setEmail("hibernateJPa03@hbm.com");
        user.setSecondName("hibernateJPa03");
        User save = userMapper.save(user);
        return save;
    }
    @Override
    public User update() {
        User user = new User();
        user.setId(5L);
        user.setAccount("hibernateJPa03");
        user.setName("hibernateJPa03");
        user.setPassword("ASWDEWSAW");
        user.setEmail("hibernateJPa03@hbm.com");
        user.setSecondName("hibernateJPa03");
        User save = userMapper.save(user);
        return save;
    }
    @Override
    public User delete() {
        User user = new User();
        user.setId(10L);
        userMapper.delete(user);
        return null;
    }
    @Override
    public User userById() {
       // Iterable<User> allById = userMapper.findAllById(Arrays.asList(1L));
        Optional<User> userOptional = userMapper.findById(4L);
        if (!userOptional.isPresent()){
            return null;
        }
        User user = userOptional.get();

        return user;
    }
}

创建controller类编写一个接口进行测试。

@RestController
@RequestMapping("/admin/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping
    public String crudUser(){
        List<User> userList = userService.findAll();
        userList.forEach(System.out::println);
        User user = userService.userById();
        System.out.println(user);
        return "操作执行成功!!!";
    }
}

调用接口执行过后,查看控制台输出。

数据查询成功。至此springboot集成JPA就完成了。里面有很多方法,时间充足可以试试不同的方法。

 补充:

通过JPA使用原生sql进行模糊查询,在Mapper接口增加一个接口方法,使用jpa的@query注解进行sql语句编写

public interface UserMapper extends JpaRepository<User,Long> , JpaSpecificationExecutor {
  #nativeQuery = true 说明启动mysql本身的sql语句进行查询 默认为false
    @Query(value = "select * from tb_user where name like concat('%',?1,'%')",nativeQuery = true)
    List<User> findOneByName(@Param("name") String name);
}

 

posted @ 2023-05-11 15:17  sowler  阅读(766)  评论(2编辑  收藏  举报