hibernate jpa 持久层技术
-
导入maven依赖
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.hibernate.version>5.0.7.Final</project.hibernate.version> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${project.hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>${project.hibernate.version}</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> </dependencies>
-
resources--->META-INF--->persistence.xml(只能放这个目录)
<?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0"> <!--配置持久化单元 在配置文件中至少有一个 name 持久化单元的名称 transaction-type 事物类型 RESOURCE_LOCAL 单数据库的事物 JTA 分布式事物 跨数据的事物 多个数据库的事物 --> <persistence-unit name="myjpa" transaction-type="RESOURCE_LOCAL"> <properties> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="root"/> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/springdata"/> <!--配置hibernate的属性--> <property name="hibernate.show_sql" value="true"></property> <!--sql语句是否格式化--> <property name="hibernate.format_sql" value="true"/> <!--是否自动创建数据库表 value 可选值 create update none create 程序自动创建数据库表 如果表存在 先删除后创建 update 程序自动创建数据库表 如果表存在 不创建 none 不会创建 --> <property name="hibernate.hbm2ddl.auto" value="update"/> </properties> </persistence-unit> </persistence>
-
编写实体类(实体类就是数据库表)
注解:@Entity
标识这个实体类是一个JPA实体,告诉JPA在程序运行的时候记得生成这个实体类所对应的表~!
@Table(name = "自定义的表名")
自定义设置这个实体类在数据库所对应的表名!
@Id
把这个类里面所在的变量设置为主键Id。
@GeneratedValue
设置主键的生成策略,这种方式依赖于具体的数据库,如果数据库不支持自增主键,那么这个类型是没法用的。
@Column(name = "自定义字段名",length = "自定义长度",nullable = "是否可以空",unique = "是否唯一",columnDefinition = "自定义该字段的类型和长度")
表示对这个变量所对应的字段名进行一些个性化的设置,例如字段的名字,字段的长度,是否为空和是否唯一等等设置。
package cn.liyang.springData.pojo; import javax.persistence.*; /** * @author liyang * @date 2019/8/14 14:41 * @description: */ @Entity @Table(name = "cust_customer") public class Customer { // 配置主键的生成策略 GenerationType.IDENTITY 自增长 @GeneratedValue(strategy = GenerationType.IDENTITY) @Id //配置属性和字段名之间关系 @Column(name="cust_id") private long custId; @Column(name="cust_name") private String custName; @Column(name="cust_source") private String custSource; @Column(name="cust_industry") private String custIndustry; @Column(name="cust_level") private String custLevel; @Column(name="cust_address") private String custAddress; @Column(name="cust_phone") private String custPhone; public long getCustId() { return custId; } public void setCustId(long custId) { this.custId = custId; } public String getCustNmae() { return custName; } public void setCustName(String custName) { this.custName = custName; } public String getCustSource() { return custSource; } public void setCustSource(String custSource) { this.custSource = custSource; } public String getCustIndustry() { return custIndustry; } public void setCustIndustry(String custIndustry) { this.custIndustry = custIndustry; } public String getCustLevel() { return custLevel; } public void setCustLevel(String custLevel) { this.custLevel = custLevel; } public String getCustAddress() { return custAddress; } public void setCustAddress(String custAddress) { this.custAddress = custAddress; } public String getCustPhone() { return custPhone; } public void setCustPhone(String custPhone) { this.custPhone = custPhone; } @Override public String toString() { return "Customer{" + "custId=" + custId + ", custName='" + custName + '\'' + ", custSource='" + custSource + '\'' + ", custIndustry='" + custIndustry + '\'' + ", custLevel='" + custLevel + '\'' + ", custAddress='" + custAddress + '\'' + ", custPhone='" + custPhone + '\'' + '}'; } }
-
测试类CRUD
package cn.liyang.springData.jpa; import cn.liyang.springData.pojo.Customer; import org.junit.Before; import org.junit.Test; import javax.persistence.*; import java.util.List; /** * @author liyang * @date 2019/8/14 15:00 * @description: */ public class JpaTest { EntityManagerFactory factory = null; @Before public void init () { factory = Persistence.createEntityManagerFactory( "myjpa" ); } //聚合函数 统计 @Test public void count(){ EntityManager entityManager = factory.createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); //这个JPQL需要写 select count(*) Query query = entityManager.createQuery( "select count(*) from Customer " ); List<Long> count = query.getResultList(); Long c = count.get( 0 ); System.out.println(c); transaction.commit(); entityManager.close(); } //排序查询 @Test public void getAllByOrder(){ EntityManager entityManager = factory.createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); Query query = entityManager.createQuery( "from Customer order by custId desc" ); List<Customer> resultList = query.getResultList(); for (Customer customer : resultList) { System.out.println(customer); } transaction.commit(); entityManager.close(); } //自定一查询条件 @Test public void selectedByName(){ EntityManager entityManager = factory.createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); //Customer相当于表名字 custName类的属性名 相当于表的字段名字 Query query = entityManager.createQuery( "from Customer where custName like ?" ); query.setParameter( 1, "%2%" ); List<Customer> resultList = query.getResultList(); for (Customer customer : resultList) { System.out.println(customer); } transaction.commit(); entityManager.close(); } //按照id查询 @Test public void selectedById () { EntityManager entityManager = factory.createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); Customer customer = entityManager.find( Customer.class, 12L ); System.out.println(customer); transaction.commit(); entityManager.close(); } //修改 @Test public void testUpdate () { EntityManager entityManager = factory.createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); Customer customer = entityManager.find( Customer.class, 2L ); customer.setCustName( "liyang" ); transaction.commit(); entityManager.close(); } //删除 @Test public void testDelete () { EntityManager entityManager = factory.createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); Customer customer = entityManager.find( Customer.class, 1L ); entityManager.remove( customer ); transaction.commit(); entityManager.close(); } //插入 @Test public void testAdd () { EntityManager entityManager = factory.createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); for (int i = 0; i < 20; i++) { Customer customer = new Customer(); customer.setCustAddress( "政七街" + i + "号" ); customer.setCustName( "员工" + i ); customer.setCustLevel( "vip:" + i + "级" ); customer.setCustPhone( "1529086641" + i ); entityManager.persist( customer ); } transaction.commit(); entityManager.close(); } @Test public void firstTest () { // 1 创键一个EntityManagerFactory 对象 使用完关闭 EntityManagerFactory factory = Persistence.createEntityManagerFactory( "myjpa" ); // 2 使用工厂对象EntityManagerFactory 就是一个连接 EntityManager entityManager = factory.createEntityManager(); // 3 开启事物 EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); // 4 创键 Customer 对象 Customer customer = new Customer(); customer.setCustName( "ruirui" ); customer.setCustLevel( "vip" ); customer.setCustSource( "网络" ); customer.setCustPhone( "123456" ); customer.setCustAddress( "懒人中心" ); // 5 使用Entitymanager 对象 的persist 方法向数据库添加数据 entityManager.persist( customer ); // 6 事物提交 transaction.commit(); // 7 关闭连接 entityManager.close(); factory.close(); } }