spring-DATA-JPA的 CRUD(增删盖该查) 和 JPQL查询

1...POM.XML文件的配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5     <modelVersion>4.0.0</modelVersion>
 6 
 7     <groupId>com.wsc</groupId>
 8     <artifactId>spring-Data-jpa</artifactId>
 9     <version>1.0-SNAPSHOT</version>
10 
11 
12     <properties>
13         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
14         <maven.compiler.source>1.8</maven.compiler.source>
15         <maven.compiler.target>1.8</maven.compiler.target>
16         <project.persistence.version>5.0.1.final</project.persistence.version>
17     </properties>
18     <dependencies>
19         <dependency>
20             <groupId>junit</groupId>
21             <artifactId>junit</artifactId>
22             <version>4.12</version>
23         </dependency>
24         <dependency>
25             <groupId>org.hibernate</groupId>
26             <artifactId>hibernate-entitymanager</artifactId>
27             <version>${project.persistence.version}</version>
28         </dependency>
29         <dependency>
30             <groupId>org.hibernate</groupId>
31             <artifactId>hibernate-c3p0</artifactId>
32             <version>5.0.9.Final</version>
33         </dependency>
34         <dependency>
35             <groupId>mysql</groupId>
36             <artifactId>mysql-connector-java</artifactId>
37             <version>5.1.6</version>
38         </dependency>
39         <dependency>
40             <groupId>log4j</groupId>
41             <artifactId>log4j</artifactId>
42             <version>1.2.17</version>
43         </dependency>
44     </dependencies>
45 </project>
pom.xml 配置

2...classpath:/META-INF/persistence.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
 3     <persistence-unit name="c3p0">
 4         <properties>
 5             <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
 6             <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/shop"/>
 7             <property name="javax.persistence.jdbc.user" value="root"/>
 8             <property name="javax.persistence.jdbc.password" value="wsc"/>
 9 <!--                格式化SQL语句-->
10             <property name="hibernate.format_sql" value="true"/>
11 <!--            console 展示SQL代码-->
12             <property name="hibernate.show_sql" value="true"/>
13             <property name="hibernate.hbm2ddl.auto" value="update"/>
14 <!--                   create    先删除后创建-->
15 <!--            ​        update  没有创建  有直接使用-->
16 <!--            ​        none   不创建-->
17         </properties>
18     </persistence-unit>
19 </persistence>
persistence.xml

3...实体类创建 及 属性说明

 1 package com.wsc.core.jpa;
 2 
 3 import javax.persistence.*;
 4 
 5 /**
 6  * @version 1.0
 7  * @ClassName Account
 8  * @Description TODO
 9  * @Author WSC
10  * @Date 2019/8/15 12:04
11  *   1   GenerationType.IDENTITY   自动增长主键   推荐mysql 使用
12  *
13  * ​       2  GenerationType.SEQUENCE   使用序列生成主键  一般是Oracle 使用 不推荐mysql使用
14  *
15  * ​      3   GenerationType.TABLE    使用数据库的表生成主键
16  *
17  * ​        @ GeneratedValue(startegy= GenerationType.TABLE,generator="tab_gen")
18  *
19  * ​        @TableGenerator(name=""tab_gen",table="ids_gen" pkColumnName="ids")
20  *
21  * ​        valueColumnName="vals",pkColumnValue="customer",allocationSize=1
22  *
23  * name   生成器的名称
24  *
25  * table   生成主键表的名称
26  *
27  *  pkColumnName   主键字段的名称
28  *
29  * valueColumnName  值  字段的名称
30  *
31  * pkColumnValue  主键字段的值
32  *
33  * ,allocationSize 生成主键的步长    默认是50
34  *
35  * ​         4  GenerationType.Auto   由框架自动选择
36  **/
37     @Entity
38     @Table(name="ac_account")
39  public class Account {
40     @GeneratedValue(strategy=GenerationType.IDENTITY)
41     @Id
42     @Column(name="ac_id")
43     private int acId;
44     @Column(name="ac_address")
45     private String acAddress;
46     @Column(name="ac_name")
47     private String acName;
48     @Column(name="ac_age")
49     private int acAge;
50 
51     public int getAcId() {
52         return acId;
53     }
54 
55     public void setAcId(int acId) {
56         this.acId = acId;
57     }
58 
59     public String getAcAddress() {
60         return acAddress;
61     }
62 
63     public void setAcAddress(String acAddress) {
64         this.acAddress = acAddress;
65     }
66 
67     public String getAcName() {
68         return acName;
69     }
70 
71     public void setAcName(String acName) {
72         this.acName = acName;
73     }
74 
75     public int getAcAge() {
76         return acAge;
77     }
78 
79     public void setAcAge(int acAge) {
80         this.acAge = acAge;
81     }
82 
83     @Override
84     public String toString() {
85         return "Account{" +
86                 "acId=" + acId +
87                 ", acAddress='" + acAddress + '\'' +
88                 ", acName='" + acName + '\'' +
89                 ", acAge=" + acAge +
90                 '}';
91     }
92 }
pojo

4...test core

1...插入数据

 1   /**
 2      * 插入数据
 3      */
 4     @Test
 5     public void test01(){
 6         // 1 创建EntityMananger 对象
 7         EntityManager entityManager = entityManagerFactory.createEntityManager();
 8         // 2 开启事物
 9         EntityTransaction transaction = entityManager.getTransaction();
10         transaction.begin();
11         // 3 创建account对象
12         Account account;
13         for(int i =0 ; i<=20; i++){
14             account = new Account();
15             account.setAcName("名字"+i+"号");
16             account.setAcAge(20+i);
17             account.setAcAddress("中心"+i+"中心");
18             entityManager.persist(account);
19         }
20          //4 提交事物
21          transaction.commit();
22         //5  关闭连接
23         entityManager.close();
24     }
插入数据

2...remove 移除一个对象

 1  /**
 2      *remove 移除一个对象
 3      */
 4     @Test
 5    public void test02(){
 6         // 1 创建EntityMananger 对象
 7         EntityManager entityManager = entityManagerFactory.createEntityManager();
 8         // 2 开启事物
 9         EntityTransaction transaction = entityManager.getTransaction();
10         transaction.begin();
11         // 3 先从数据库中 创建account对象
12         Account account = entityManager.find(Account.class, 1);
13         System.out.println(account);
14         //4 使用entityManager对象 remove方法删除   参数就是account对象
15         entityManager.remove(account);
16         //5 提交事物
17         transaction.commit();
18         //6  关闭连接
19         entityManager.close();
20     }
移除数据

3...更新 merge

 1  /**
 2      * 更新 merge
 3      */
 4     @Test
 5     public void test03(){
 6         // 1 创建EntityMananger 对象
 7         EntityManager entityManager = entityManagerFactory.createEntityManager();
 8         // 2 开启事物
 9         EntityTransaction transaction = entityManager.getTransaction();
10         transaction.begin();
11         //3 根据id  find  account
12         Account account = entityManager.find(Account.class,2);
13         account.setAcAddress("蓝底中西节");
14         account.setAcAge(100);
15         // 5 修改的结构保存到数据库
16         entityManager.merge(account);
17         //6 提交事物
18         transaction.commit();
19         //7  关闭连接
20         entityManager.close();
21     }
更新数据

4...根据id查 find 方法

 1  /**
 2      *  根据id查 find 方法
 3      */
 4     @Test
 5     public void test04(){
 6         // 1 创建EntityMananger 对象
 7         EntityManager entityManager = entityManagerFactory.createEntityManager();
 8         Account account = entityManager.find(Account.class, 2);
 9         System.out.println("find方法查询结果");
10         System.out.println(account+"find方法查询结果");
11         //2  关闭连接
12         entityManager.close();
13     }
根据id查 find 方法

5...根据id查 getReference 方法

 1  /**
 2      *  根据id查 getReference 方法
 3      */
 4     @Test
 5     public void test05(){
 6         // 1 创建EntityMananger 对象
 7         EntityManager entityManager = entityManagerFactory.createEntityManager();
 8         Account account = entityManager.getReference(Account.class,2);
 9         System.out.println("getReference方法查询结果");
10         System.out.println(account+"getReference方法查询结果");
11         //2  关闭连接
12         entityManager.close();
13     }
根据id查 getReference 方法

6...  JPQL查询

 1  /**
 2      * findAll 方法
 3      * 基于jpql 创建
 4      * 创建一个Query对象
 5      *
 6      ​      1   查询全部
 7      ​        sql :select * from ac_account
 8      ​        jpql: from account   实体的类名
 9      *
10      */
11     @Test
12     public void test06(){
13         // 1 创建EntityMananger 对象
14         EntityManager entityManager = entityManagerFactory.createEntityManager();
15         // 使用EntryManager 创建一个Query对象  基于jpql 创建
16         // 参数  就是jpql 语句
17         Query from_account = entityManager.createQuery("from Account");
18         //  使用query对象 执行查询
19         List<Account> resultList = from_account.getResultList();
20         // 打印结果
21         for(Account result:resultList){
22             System.out.println(result);
23         }
24         entityManager.close();
25     }
findAll

7...

 1 /**
 2      * 分页查询数据
 3      * sleect * from ac_account LIMIT 0,10
 4      * from Account
 5      * setFirstResult 开始查询点
 6      * setMaxResults   结束查询点
 7      */
 8     @Test
 9     public void test07(){
10 // 1 创建EntityMananger 对象
11         EntityManager entityManager = entityManagerFactory.createEntityManager();
12         // 使用EntryManager 创建一个Query对象  基于jpql 创建
13         // 参数  就是jpql 语句
14         Query from_account = entityManager.createQuery("from Account");
15         //设置分页信息
16         from_account.setFirstResult(0);
17         from_account.setMaxResults(5);
18         // 执行查询
19         List<Account> resultList = from_account.getResultList();
20         for(Account list:resultList){
21             System.out.println(list);
22         }
23         entityManager.close();
24     }
分页查询数据

8...

 1 /**
 2      * sql :   select * from ac_account where ac_id=?
 3      *
 4      * ​          jpql:  from Account where acId=?
 5      * //  jpql按id 查
 6      * 设置参数
 7      * 占位符
 8      * id 值
 9      * setParameter(1, 2)
10      */
11     @Test
12     public void test08(){
13         // 1 创建EntityMananger 对象
14         EntityManager entityManager = entityManagerFactory.createEntityManager();
15         // 使用EntryManager 创建一个Query对象  基于jpql 创建
16         // 参数  就是jpql 语句
17         Query query = entityManager.createQuery("from Account where acId=?");
18         // 设置参数
19         query.setParameter(1, 2);
20         //执行查询
21         Account singleResult = (Account) query.getSingleResult();
22         System.out.println(singleResult);
23         entityManager.close();
24     }
jpql按id 查

9...

 1 /**
 2      *模糊查询
 3      * sql:select * from ac_account where ac_name like  '%2%'
 4      *
 5      * ​        jspl:from Account where acName like ?
 6      */
 7     @Test
 8     public void test09(){
 9         // 1 创建EntityMananger 对象
10         EntityManager entityManager = entityManagerFactory.createEntityManager();
11         // 使用EntryManager 创建一个Query对象  基于jpql 创建
12         // 参数  就是jpql 语句
13         Query query = entityManager.createQuery("from Account where acName like ?");
14         // 设置参数
15         query.setParameter(1,"%2%");
16 
17         List<Account> resultList = query.getResultList();
18         for(Account list:resultList){
19             System.out.println(list);
20         }
21         entityManager.close();
22     }
模糊查询

10...

 1  /**
 2      *
 3       查询   排序
 4 
 5      ​    sql   select * from cst_customer order by cust_id desc
 6 
 7      ​      jpql:from Customer oreder by custId desc
 8      */
 9     @Test
10     public void test10(){
11         // 1 创建EntityMananger 对象
12         EntityManager entityManager = entityManagerFactory.createEntityManager();
13         // 使用EntryManager 创建一个Query对象  基于jpql 创建
14         // 参数  就是jpql 语句
15         Query query = entityManager.createQuery("from Account order by acAge desc");
16         List<Account> resultList = query.getResultList();
17         for(Account list:resultList){
18             System.out.println(list);
19         }
20         entityManager.close();
21     }
查询 排序

11...

 1  /**
 2      * 聚合函数
 3      *
 4      * ​        sql :  select count(*) from ac_account
 5      *
 6      * ​        jpql:select count(*) from  Account
 7      */
 8     @Test
 9     public void test11(){
10         // 1 创建EntityMananger 对象
11         EntityManager entityManager = entityManagerFactory.createEntityManager();
12         // 使用EntryManager 创建一个Query对象  基于jpql 创建
13         // 参数  就是jpql 语句
14         Query query = entityManager.createQuery("select count(*) from Account");
15 //        Query query = entityManager.createQuery("select count(1) from Account");
16         Object count = query.getSingleResult();
17         System.out.println(count);
18         entityManager.close();
19     }
聚合函数

以上综合代码

  1 package com.wsc.core.test;
  2 
  3 import com.wsc.core.jpa.Account;
  4 import org.junit.Before;
  5 import org.junit.Test;
  6 
  7 import javax.persistence.*;
  8 import java.util.List;
  9 
 10 /**
 11  * @version 1.0
 12  * @ClassName TestJPA
 13  * @Description TODO
 14  * @Author WSC
 15  * @Date 2019/8/15 13:59
 16  *
 17  * EntityMananger:
 18  *
 19  * ​            添加:persist
 20  *
 21  * ​            删除  remove
 22  *
 23  * ​            修改  merge
 24  *
 25  * ​            查询  find
 26  *
 27  * ​                getReference
 28  **/
 29 public class TestJPA {
 30     private EntityManagerFactory entityManagerFactory;
 31      @Before
 32      public void createEntityManager(){
 33            entityManagerFactory = Persistence.createEntityManagerFactory("c3p0");
 34      }
 35 
 36     /**
 37      * 插入数据
 38      */
 39     @Test
 40     public void test01(){
 41         // 1 创建EntityMananger 对象
 42         EntityManager entityManager = entityManagerFactory.createEntityManager();
 43         // 2 开启事物
 44         EntityTransaction transaction = entityManager.getTransaction();
 45         transaction.begin();
 46         // 3 创建account对象
 47         Account account;
 48         for(int i =0 ; i<=20; i++){
 49             account = new Account();
 50             account.setAcName("名字"+i+"号");
 51             account.setAcAge(20+i);
 52             account.setAcAddress("中心"+i+"中心");
 53             entityManager.persist(account);
 54         }
 55          //4 提交事物
 56          transaction.commit();
 57         //5  关闭连接
 58         entityManager.close();
 59     }
 60     /**
 61      *remove 移除一个对象
 62      */
 63     @Test
 64    public void test02(){
 65         // 1 创建EntityMananger 对象
 66         EntityManager entityManager = entityManagerFactory.createEntityManager();
 67         // 2 开启事物
 68         EntityTransaction transaction = entityManager.getTransaction();
 69         transaction.begin();
 70         // 3 先从数据库中 创建account对象
 71         Account account = entityManager.find(Account.class, 1);
 72         System.out.println(account);
 73         //4 使用entityManager对象 remove方法删除   参数就是account对象
 74         entityManager.remove(account);
 75         //5 提交事物
 76         transaction.commit();
 77         //6  关闭连接
 78         entityManager.close();
 79     }
 80 
 81         /**
 82          * 更新 merge
 83          */
 84         @Test
 85         public void test03(){
 86             // 1 创建EntityMananger 对象
 87             EntityManager entityManager = entityManagerFactory.createEntityManager();
 88             // 2 开启事物
 89             EntityTransaction transaction = entityManager.getTransaction();
 90             transaction.begin();
 91             //3 根据id  find  account
 92             Account account = entityManager.find(Account.class,2);
 93             account.setAcAddress("蓝底中西节");
 94             account.setAcAge(100);
 95             // 5 修改的结构保存到数据库
 96             entityManager.merge(account);
 97             //6 提交事物
 98             transaction.commit();
 99             //7  关闭连接
100             entityManager.close();
101         }
102 
103     /**
104      *  根据id查 find 方法
105      */
106     @Test
107     public void test04(){
108         // 1 创建EntityMananger 对象
109         EntityManager entityManager = entityManagerFactory.createEntityManager();
110         Account account = entityManager.find(Account.class, 2);
111         System.out.println("find方法查询结果");
112         System.out.println(account+"find方法查询结果");
113         //2  关闭连接
114         entityManager.close();
115     }
116     /**
117      *  根据id查 getReference 方法
118      */
119     @Test
120     public void test05(){
121         // 1 创建EntityMananger 对象
122         EntityManager entityManager = entityManagerFactory.createEntityManager();
123         Account account = entityManager.getReference(Account.class,2);
124         System.out.println("getReference方法查询结果");
125         System.out.println(account+"getReference方法查询结果");
126         //2  关闭连接
127         entityManager.close();
128     }
129 
130 //    JPQL查询
131 
132     /**
133      * findAll 方法
134      * 基于jpql 创建
135      * 创建一个Query对象
136      *
137      ​      1   查询全部
138      ​        sql :select * from ac_account
139      ​        jpql: from account   实体的类名
140      *
141      */
142     @Test
143     public void test06(){
144         // 1 创建EntityMananger 对象
145         EntityManager entityManager = entityManagerFactory.createEntityManager();
146         // 使用EntryManager 创建一个Query对象  基于jpql 创建
147         // 参数  就是jpql 语句
148         Query from_account = entityManager.createQuery("from Account");
149         //  使用query对象 执行查询
150         List<Account> resultList = from_account.getResultList();
151         // 打印结果
152         for(Account result:resultList){
153             System.out.println(result);
154         }
155         entityManager.close();
156     }
157 
158     /**
159      * 分页查询数据
160      * sleect * from ac_account LIMIT 0,10
161      * from Account
162      * setFirstResult 开始查询点
163      * setMaxResults   结束查询点
164      */
165     @Test
166     public void test07(){
167 // 1 创建EntityMananger 对象
168         EntityManager entityManager = entityManagerFactory.createEntityManager();
169         // 使用EntryManager 创建一个Query对象  基于jpql 创建
170         // 参数  就是jpql 语句
171         Query from_account = entityManager.createQuery("from Account");
172         //设置分页信息
173         from_account.setFirstResult(0);
174         from_account.setMaxResults(5);
175         // 执行查询
176         List<Account> resultList = from_account.getResultList();
177         for(Account list:resultList){
178             System.out.println(list);
179         }
180         entityManager.close();
181     }
182 
183     /**
184      * sql :   select * from ac_account where ac_id=?
185      *
186      * ​          jpql:  from Account where acId=?
187      * //  jpql按id 查
188      * 设置参数
189      * 占位符
190      * id 值
191      * setParameter(1, 2)
192      */
193     @Test
194     public void test08(){
195         // 1 创建EntityMananger 对象
196         EntityManager entityManager = entityManagerFactory.createEntityManager();
197         // 使用EntryManager 创建一个Query对象  基于jpql 创建
198         // 参数  就是jpql 语句
199         Query query = entityManager.createQuery("from Account where acId=?");
200         // 设置参数
201         query.setParameter(1, 2);
202         //执行查询
203         Account singleResult = (Account) query.getSingleResult();
204         System.out.println(singleResult);
205         entityManager.close();
206     }
207 
208     /**
209      *模糊查询
210      * sql:select * from ac_account where ac_name like  '%2%'
211      *
212      * ​        jspl:from Account where acName like ?
213      */
214     @Test
215     public void test09(){
216         // 1 创建EntityMananger 对象
217         EntityManager entityManager = entityManagerFactory.createEntityManager();
218         // 使用EntryManager 创建一个Query对象  基于jpql 创建
219         // 参数  就是jpql 语句
220         Query query = entityManager.createQuery("from Account where acName like ?");
221         // 设置参数
222         query.setParameter(1,"%2%");
223 
224         List<Account> resultList = query.getResultList();
225         for(Account list:resultList){
226             System.out.println(list);
227         }
228         entityManager.close();
229     }
230 
231     /**
232      *
233       查询   排序
234 
235      ​    sql   select * from cst_customer order by cust_id desc
236 
237      ​      jpql:from Customer oreder by custId desc
238      */
239     @Test
240     public void test10(){
241         // 1 创建EntityMananger 对象
242         EntityManager entityManager = entityManagerFactory.createEntityManager();
243         // 使用EntryManager 创建一个Query对象  基于jpql 创建
244         // 参数  就是jpql 语句
245         Query query = entityManager.createQuery("from Account order by acAge desc");
246         List<Account> resultList = query.getResultList();
247         for(Account list:resultList){
248             System.out.println(list);
249         }
250         entityManager.close();
251     }
252 
253     /**
254      * 聚合函数
255      *
256      * ​        sql :  select count(*) from ac_account
257      *
258      * ​        jpql:select count(*) from  Account
259      */
260     @Test
261     public void test11(){
262         // 1 创建EntityMananger 对象
263         EntityManager entityManager = entityManagerFactory.createEntityManager();
264         // 使用EntryManager 创建一个Query对象  基于jpql 创建
265         // 参数  就是jpql 语句
266         Query query = entityManager.createQuery("select count(*) from Account");
267 //        Query query = entityManager.createQuery("select count(1) from Account");
268         Object count = query.getSingleResult();
269         System.out.println(count);
270         entityManager.close();
271     }
272 }
全部代码实现 CRUD

 

猜你喜欢

转载自www.cnblogs.com/wangshichang/p/11358807.html