Preface:
Based on the Spring Framework 4.x or Spring Boot 1.x development environment
It is important to note the following version issues:
Spring framework4.x (Spring boot1.x) corresponds to spring-data1.x
Spring framework5.x (Spring boot2.x) corresponds to spring-data2.x
One, dependence
Requires JPA 1.x,hibernate 5.X,SPRING-DATA-COMMONS,SPRING-DATA-JPA
Maven mode:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId> hibernate-jpa-2.1-api</artifactid>
<version>1.0.2.Final</version>
</dependency >
<dependency>
<groupId>org.hibernate</groupId>
<artifactId> hibernate-core</artifactid>
<version>5.2.16.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId> hibernate-entitymanager</artifactid>
<version>5.2.16.Final</version>
</ dependency>
<dependency>
<groupId>org.springframework.data</groupId>
< artifactid>spring-data-jpa</artifactid>
<version>1.11.11.RELEASE</version>
< /dependency>
Second, the environment configuration
Note Two scanners (one is the PO entity class Scan, and the other is the DAO Layer interface Scan)
<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:
Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context"
xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns:jpa= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/DATA/JPA" xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/DATA/JPA http://www.springframework.org/schema/data/jpa/ Spring-jpa.xsd > <!--eguid Blog All original articles are licensed under the Creative Commons Attribution-Share 3.0 Chinese mainland license agreement in the same way. If reproduced please specify the blog address:https://blog.csdn.net/eguid_1/article/details/80018676--> <!--druid Connection pool--<bean id= " DataSource "class=" Com.alibaba.Druid.pool.DruidDataSource "init-method=" Init "destroy-method=" close "> <property name=" driverclassname "Valu E= "${jdbc.driverclassname}"/> <property name= "url" value= "${jdbc.url}"/> <property name= "username" value = "${jdbc.username}"/> <property name= "password" value= "${jdbc.password}"/> <property name= "maxActive" va Lue= "${jdbc.maxactive}"/> <property name= "initialsize" value= "${jdbc.initialsize}"/> <property name= "Ma Xwait "value=" ${jdbc.maxwait} "/> <property name=" Maxidle "value=" ${jdbc.maxidle} "/> <property name=" MinI Dle "value=" ${jdbc.minidle} "/> <property name=" removeabandoned "value=" ${jdbc.removeabandoned} "/> <prop Erty name= "Removeabandonedtimeout" value= "${jdbc.removeabandonedtimeout}"/> <property name= "TestWhileIdle" Value= "${jdbc.testwhileidle}"/> <property name= "validationquery" value= "${jdbc.validationquery}"/> < Property Name= "Validationquerytimeout"Value=" ${jdbc.validationquerytimeout} "/> <property name=" Timebetweenevictionrunsmillis "value=" ${ Jdbc.timebetweenevictionrunsmillis} "/> <property name=" Numtestsperevictionrun "value=" ${ Jdbc.numtestsperevictionrun} "/> <!--open Pscache and specify the size of Pscache on each connection--   ; <property name= "Poolpreparedstatements" value= "false"/> &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&N Bsp; <property name= "maxpoolpreparedstatementperconnectionsize" value= "/> &nbs" p; <!--Configuration Monitoring Statistics interception filters-- & Lt;property name= "Filters" value= "Stat,wall"/> <property nam E= "ConnectionProperties" value= "druid.stat.slowsqlmillis=5000"/> </bean> <!--JPA Factory objects--<bean ID = "Entitymanagerfactory" class= "Org.springframework.orm.jpa.LocalConTainerentitymanagerfactorybean "> <property name=" dataSource "ref=" DataSource "/> &nbs p; <!--Scan all entities under this package for ORM Mapping (where the entity class package path needs to be modified)- &nbs P; <property name= "Packagestoscan" value= "Cc.eguid.xxx.pojo.po"/> < Property name= "Persistenceprovider" > <bean class= "org.hibernate.jpa.HibernatePersis Tenceprovider "/> </property> <property name=" Jpaven Doradapter "> <bean class=" org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter "> &L
T;property name= "Generateddl" value= "false"/> <property name= "database" value= "MYSQL"/> <property name= "Databaseplatform" value= "Org.hibernate.dialect.MySQLDialect"/> <property name= "s
Howsql "value=" true "/> </bean> </property> <property name= "Jpadialect" > <bean class= "Org.springfram
Ework.orm.jpa.vendor.HibernateJpaDialect "/> </property> <property name=" Jpapropertymap "> <map> <entry key= "Hibernate.query.substitutions" value= "True 1, False 0"/> <en Try key= "hibernate.default_batch_fetch_size" value= "/> <entry key=" hibernate.max_fetch_depth "value = "2"/> <entry key= "Hibernate.generate_statistics" value= "true"/> <entry key= "Hiber Nate.bytecode.use_reflection_optimizer "value=" true "/> <entry key=" Hibernate.cache.use_second_level_ca Che "value=" false "/> <entry key=" Hibernate.cache.use_query_cache "value=" false "/> </ma p> </property> </bean> <!--Use declarative transaction management--&NBSP ; <tX:annotation-driven transaction-manager= "TransactionManager" proxy-target-class= "true"/> <!--JPA transaction Manager--<bean id= "TransactionManager" class= "Org.springframework.orm.jpa.JpaTransactionMan Ager "> <property name=" entitymanagerfactory "ref=" entitymanagerfactory "/> </bean> &n bsp; <!--Scan the JPA persistence interface, SPRING-DATA-JPA automatically generates the implementation class (where the Repostory interface package path needs to be modified)- <jpa:repositories base-package= "Cc.eguid.xxx.dao" entity-manager-factory-ref= "Entitymanagerfactory"
transaction-manager-ref= "TransactionManager"/> </beans>
third, entity class and Repository interface
(1) Writing the DAO Layer Interface (No implementation class is required, SPRING-DATA-JPA automatically generates the implementation class)
Import org.springframework.data.repository.CrudRepository;
/**
* SPRING-DATA-JPA automatically generates implementation classes to simplify DAO layer development
* @author EGUID * */public
interface userrepository Extends crudrepository<gameuserinfo, integer>{
gameuserinfo findbyusername (String username);
}
(2) Auto-generated ORM mapping entity (generated with JPA generation tools)
/** * The persistent class for the Game_userinfo database table. * */@Entity @Table (name= "userinfo") @NamedQuery (name= "Userinfo.findall", query= "Select G from UserInfo G") public class
Userinfo extends BaseEntity {private static final long serialversionuid = 1L;
@Id @GeneratedValue (Strategy=generationtype.auto) @Column (Unique=true, Nullable=false) private Integer userid;
Private Timestamp Createtime;
@Column (length=50) private String nickname;
@Column (length=100) private String password;
private int type;
@Column (length=50) private String username; Bi-directional Many-to-many Association to Roleinfo @ManyToMany @JoinTable (name= "Userrole", joincolumns={@Jo
Incolumn (name= "userid", Nullable=false)}, inversejoincolumns={@JoinColumn (name= "Roleid", Nullable=false)}
) Private list<roleinfo> Roleinfos;
Public Userinfo () {} public Integer GetUserid () {return this.userid; } public void Setuserid (Integer userid) {this.UserID = userid;
} public Timestamp Getcreatetime () {return this.createtime;
} public void Setcreatetime (Timestamp createtime) {this.createtime = Createtime;
} public String Getnickname () {return this.nickname;
} public void Setnickname (String nickname) {this.nickname = nickname;
} public String GetPassword () {return this.password;
} public void SetPassword (String password) {this.password = password;
} public int GetType () {return this.type;
} public void SetType (int type) {this.type = type;
} public String GetUserName () {return this.username;
} public void Setusername (String username) {this.username = username;
} public list<roleinfo> Getroleinfos () {return this.roleinfos;
} public void Setroleinfos (list<roleinfo> roleinfos) {This.roleinfos = Roleinfos; }
}
Iv. Summary
1. Add dependencies (add Spring-data and SPRING-DATA-JPA dependency packages)
2. Configure the JPA environment (configure DAO Scan path and entity class scan path)
3, write the Entity class and DAO layer interface (if it is simple single table additions and deletions to the operation, directly inherit the Crudrepository interface can, basically do not need to write code)
JPA Single-table operations are almost impeccable, involving multi-table operations requiring handwritten HQL statements or JPA
Entity classes are built with tools, so you can actually just write a DAO interface