Preface:
Based on the Spring Framework 4.x or Spring Boot 1.x development environment
Note the following version problems: Spring framework4.x(Spring Boot1.x) corresponds to Spring-data1.x
Spring framework5.x(Spring boot2.x) corresponds to spring-data2.x
A, rely on
You need JPA 1.x, Hibernate 5.x, spring-data-Commons, spring-data-jPA
Maven:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>Hibernate jpa 2.1 - API</artifactId>
<version>1.0.2. The Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.16. The Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.16. The Final</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.11. RELEASE</version>
</dependency>
Copy the code
Two, environment configuration
Note two scanners (one Po entity class scan and one DAO layer interface scan)
<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">
<! All original articles on Eguid blog are licensed under creative Commons Attribution - Share Alike 3.0 Mainland China License. If there is a reprint please indicate the blog: 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" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="${jdbc.maxActive}" />
<property name="initialSize" value="${jdbc.initialSize}" />
<property name="maxWait" value="${jdbc.maxWait}" />
<property name="maxIdle" value="${jdbc.maxIdle}" />
<property name="minIdle" value="${jdbc.minIdle}" />
<property name="removeAbandoned" value="${jdbc.removeAbandoned}" />
<property 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}" />
<! Turn on PSCache and specify the size of PSCache on each connection.
<property name="poolPreparedStatements" value="false" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
<! -- Configure filters to monitor statistics interception -->
<property name="filters" value="stat,wall"/>
<property name="connectionProperties" value="druid.stat.slowSqlMillis=5000" />
</bean>
<! -- JPA factory object -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<! -- Scan all entities under this package for ORM mapping -->
<property name="packagesToScan" value="cc.eguid.xxx.pojo.po" />
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider" />
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="false" />
<property name="database" value="MYSQL" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.query.substitutions" value="true 1, false 0" />
<entry key="hibernate.default_batch_fetch_size" value="16" />
<entry key="hibernate.max_fetch_depth" value="2" />
<entry key="hibernate.generate_statistics" value="true" />
<entry key="hibernate.bytecode.use_reflection_optimizer" value="true" />
<entry key="hibernate.cache.use_second_level_cache" value="false" />
<entry key="hibernate.cache.use_query_cache" value="false" />
</map>
</property>
</bean>
<! Use declarative transaction management -->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
<! -- JPA transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<! -- Scan JPA persistence interface, spring-data-jPA automatically generates implementation class (repoStory interface package path needs to be changed here)-->
<jpa:repositories base-package="cc.eguid.xxx.dao" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager"/>
</beans>
Copy the code
Entity class and Repository interface
(1) Write dao layer interface (no implementation class is required, spring-Data-JPA will automatically generate 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) Automatically generated ORM mapping Entity (generated with JPA generation tool)/** * 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={ @JoinColumn(name="userid", nullable=false) } , inverseJoinColumns={ @JoinColumn(name="roleid", nullable=false) } )
private List<roleinfo> roleinfos;
public Userinfo(a) {}public Integer getUserid(a) {
return this.userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public Timestamp getCreatetime(a) {
return this.createtime;
}
public void setCreatetime(Timestamp createtime) {
this.createtime = createtime;
}
public String getNickname(a) {
return this.nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPassword(a) {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public int getType(a) {
return this.type;
}
public void setType(int type) {
this.type = type;
}
public String getUsername(a) {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public List<Roleinfo> getRoleinfos(a) {
return this.roleinfos;
}
public void setRoleinfos(List<Roleinfo> roleinfos) {
this.roleinfos = roleinfos; }}Copy the code
Four,
1. Add dependencies (add spring-data and spring-data-jPA dependencies)
2. Configure jPA environment (configure DAO scan path and entity class scan path)
3. Write entity classes and DAO layer interfaces (CrudRepository interface can be inherited directly for simple single table add, delete, change and query operations, with little need to write code)
Jpa single table operations are basically impeccable. Multiple table operations require handwritten HQL statements or JPA.
The entity classes are tool-generated, so you really only need to write a DAO interface.