hibernate及SpringBoot整合Jpa實現對資料庫操作

sowler發表於2023-05-11

首先使用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就完成了。裡面有很多方法,時間充足可以試試不同的方法。

 

相關文章