使用JPA-Hibernate访问SQL Database

version 1.5.7

安装

在你的pom.xml文件中加上以下依赖:

  1. <dependency>
  2. <groupId>org.actframework</groupId>
  3. <artifactId>act-hibernate</artifactId>
  4. <version>1.5.7</version>
  5. </dependency>

根据你的数据库类型,你也需要加入相应的JDBC访问包的依赖。比如:

  1. <dependency>
  2. <groupId>com.h2database</groupId>
  3. <artifactId>h2</artifactId>
  4. <version>1.4.178</version>
  5. </dependency>

你还需要引入一个数据库连接池,根据自身条件在以下任选其一:

  1. <dependency>
  2. <groupId>com.zaxxer</groupId>
  3. <artifactId>HikariCP-java7</artifactId>
  4. <version>2.4.13</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.zaxxer</groupId>
  8. <artifactId>HikariCP</artifactId>
  9. <version>2.7.9</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>com.alibaba</groupId>
  13. <artifactId>druid</artifactId>
  14. <version>1.1.16</version>
  15. </dependency>

配置

  1. # If you have only one DBPlugin in your class path, then
  2. # you do not need to specify the db.impl configuration
  3. db.impl=act.db.hibernate.HibernatePlugin
  4. # database driver default to org.h2.Driver
  5. db.driver=...
  6. # database Url default to jdbc:h2:mem:tests
  7. db.url=...
  8. # username default is empty
  9. db.username=...
  10. # password default is empty
  11. db.password=...

域模型

下面创建一个简单的域模型,该模型有三个字段:

  1. id
  2. password
  3. phone
  4. email
  1. package com.mycom.myprj;
  2. import act.util.SimpleBean;
  3. import javax.persistence.*;
  4. @Entity
  5. @Table(name = "user")
  6. public class User{
  7. @Id
  8. @GeneratedValue(strategy = GenerationType.IDENTITY)
  9. private Integer id;
  10. @Column
  11. private String password;
  12. @Column
  13. private String email;
  14. @Column
  15. private String phone;
  16. public Integer getId() {
  17. return id;
  18. }
  19. public void setId(Integer id) {
  20. this.id = id;
  21. }
  22. public String getPassword() {
  23. return password;
  24. }
  25. public void setPassword(String password) {
  26. this.password = password;
  27. }
  28. public String getEmail() {
  29. return email;
  30. }
  31. public void setEmail(String email) {
  32. this.email = email;
  33. }
  34. public String getPhone() {
  35. return phone;
  36. }
  37. public void setPhone(String phone) {
  38. this.phone = phone;
  39. }
  40. }

数据库访问层

Dao 只需要很简单的 继承自 act.db.jpa.JPADao 就行了。

  1. package com.mycom.myprj;
  2. import act.db.jpa.JPADao;
  3. import com.mycom.myprj.User;
  4. public class UserDao extends JPADao<Integer,User> {
  5. }