4.使用JPA(Hibernate)操作數據庫

3. 使用JPA(Hibernate)操作數據庫

在springboot中的JPA是依賴Hibernate實現的。在Maven中引入spring-boot-starter-data-jpa,就能夠使用JPA編程了。在現在的技術潮流中,springboot已經基本轉向Mybats來操作數據庫了,較少的使用Hibernate,這裏做簡單的介紹。這裏測試在數據庫中建立一張user表,通過JPA實現用戶查詢操作。

3.1 配置數據庫連接參數

在引入starter後會有默認的配置,但是我們需要修改數據連接的基本參數才能正確連接。

# 數據庫連接驅動類,spring會自動判斷,可以省略
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mxlei?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=root
# 最大等待連接中的數量,默認0表示沒有限制
spring.datasource.tomcat.max-idle=10
# 最大活動連接數
spring.datasource.tomcat.max-active=50
# 最大等待毫秒數
spring.datasource.tomcat.max-wait=10000
# 數據庫連接初始化連接數
spring.datasource.tomcat.initial-size=5
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

3.2 定義數據庫表和POJO

POJO是指簡單Java實體類,用於數據表和Java對象的映射關係。

@Entity(name = "user")
@Table(name = "user")
@JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler"})
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id = null;

    @Column(name = "name")
    private String name = null;

    @Column(name = "note")
    private String note = null;

    @Convert(converter = SexConverter.class)
    @Column(name = "sex")
    private SexEnum sex = null;
    //省略setter/getter
}

在數據中用戶的性別是用int表示的,1代表男,0代表女。而在Java編程中不希望使用int表示性別,使用枚舉會更方便,這裏安裝JPA的規則編寫一個字段轉行器。

public enum SexEnum {

    MALE(1, "男"),
    FEMALE(0, "女");

    private int id;
    private String name;

    SexEnum(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public static SexEnum getById(int id) {
        for (SexEnum sex : SexEnum.values()) {
            if (sex.id == id) {
                return sex;
            }
        }
        return null;
    }
}
public class SexConverter implements AttributeConverter<SexEnum, Integer> {
    //將枚舉轉換爲序列
    @Override
    public Integer convertToDatabaseColumn(SexEnum sexEnum) {
        return sexEnum.getId();
    }
    //將數據庫序列轉換爲枚舉
    @Override
    public SexEnum convertToEntityAttribute(Integer integer) {
        return SexEnum.getById(integer);
    }
}

3.3 編寫數據庫操作接口

在JPA中有默認的數據庫操作接口JpaRepository,該接口有操作數據庫的基本方法,我們只需要繼承該接口即可。

@Repository
public interface JpaUserRepository extends JpaRepository<User, Long> {

    List<User> findUserByNameLike(String name);

    User findUserById(Long id);

}

根據前面講到的,spring使用動態代理的方式實現接口的織入流程。在這裏我們只需要編寫數據庫操作接口,不需要編寫任何的SQL語句、數據庫連接、事務、關閉等代碼即可實現數據庫的操作。也不需要編寫這個類的實現類。spring會自動掃描到這個接口,然後添加到IOC容器中,使用的時候只需要@AutoWired引用bean即可。

3.4 編寫Controller測試

@Controller
@RequestMapping("/jpa")
public class JpaController {

    @Autowired
    private JpaUserRepository jpaUserRepository;

    @RequestMapping("/getUser")
    @ResponseBody
    public User getUser(Long id){
        User user = jpaUserRepository.findUserById(id);
        return user;
    }

    @RequestMapping("/getUserNameLike")
    @ResponseBody
    public List<User> getUser(String name){
        System.out.println(name);
        return jpaUserRepository.findUserByNameLike(name);
    }
}

正確返回結果

{"id":1,"name":"mxlei","note":"lei","sex":"MALE"}
發佈了123 篇原創文章 · 獲贊 201 · 訪問量 33萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章