入门Spring Data-Spring整合HibernateJPA
由于Spring Data-SpringJPA是基于HibernateJPA实现的在这里进行进一步的整合。
环境:
window 10
JDK 1.8
Version: Mars.2 Release (4.5.2)
MySQL 5.7
Spring 4.2.0
Hibernate 5.0.7 Final
使用C3P0连接池 等
基本步骤
- 创建Spring配置文件applicationContext.xml
- 读取外部文件
- 配置数据库连接池C3P0,DRUID,DBCP
- 配置Hibernate通过EntityManagerFactory创建基于JPA的SessionFactory对象
- EntityManagerFactory注入JpaVendorAdapter对象,用于检测是基于什么实现JPA会规范
- 在JpaVendorAdapter中配置Hibernate的通用配置,正向工程(generateDdl),显示执行的额SQL语句(showSql)
- 配置包扫描将POJO对象进行orm映射
- 通过JpaTransactionManager.配置事务管理
- 开启事务注解管理
- 开启SpringIOC的包扫描
开始配置 - 创建JavaProject项目,导入Junit4包方便单元测试
- 创建lib文件夹保存JAR包
- 配置applicationContext.xml配置文件
<?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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
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-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!--读取外部文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!--配置数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="driverClass" value="${jdbc.driver.class}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!--配置Spring整合JPA 配置EntityManagerFactory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--jpaVendorAdapter 返回一个是基于谁实现的JPA规范 -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!--hibertnate配置 -->
<!--设置数据库类型 -->
<property name="database" value="MYSQL" />
<!--配置JPA正向工程 -->
<property name="generateDdl" value="true" />
<!--显示执行的SQL语句 -->
<property name="showSql" value="true" />
</bean>
</property>
<!--配置POJO 的映射 -->
<property name="packagesToScan">
<list>
<value>com.OVA.pojo</value>
</list>
</property>
</bean>
<!--开启事务管理 -->
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!--配置事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!--配置spring 的注解扫描 -->
<context:component-scan base-package="com.OVA" />
</beans>
- 配置jdbc.properties外置文件
jdbc.url=jdbc:mysql:///springboot
jdbc.driver.class=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=666888
- 项目分包:截图上面已经上传
- pojo创建对象实现序列化
package com.OVA.pojo;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@SuppressWarnings("serial")
@Entity
@Table(name = "users")
public class Users implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)//设置主键自增
@Column(name="userid")
private Integer userid;
@Column(name="username")
private String username;
@Column(name="userage")
private Integer userage;
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getUserage() {
return userage;
}
public void setUserage(Integer userage) {
this.userage = userage;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((userage == null) ? 0 : userage.hashCode());
result = prime * result + ((userid == null) ? 0 : userid.hashCode());
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Users other = (Users) obj;
if (userage == null) {
if (other.userage != null)
return false;
} else if (!userage.equals(other.userage))
return false;
if (userid == null) {
if (other.userid != null)
return false;
} else if (!userid.equals(other.userid))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
@Override
public String toString() {
return "Users [userid=" + userid + ", username=" + username + ", userage=" + userage + "]";
}
}
- dao创建持久层接口
package com.OVA.dao;
import java.util.List;
import com.OVA.pojo.Users;
public interface UserDao {
void insertUsers(Users users );
void updateUsres(Users users );
void deleteUsers(Users users );
Users selectUsersByID(Integer userid );
List<Users> selectUserByName(String username);
List<Users> selectUserByNameUseSQL(String username);
List<Users> selectUserByNameUseCriteria(String username);
}
- impl实现持久层接口
package com.OVA.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Repository;
import com.OVA.dao.UserDao;
import com.OVA.pojo.Users;
@Repository
public class UserDaoImpl implements UserDao {
@PersistenceContext(name = "entityManagerFactory")
private EntityManager entityManager;
@Override
public void insertUsers(Users users) {
// TODO Auto-generated method stub
entityManager.persist(users);// persist:持续存在
}
@Override
public void updateUsres(Users users) {
// TODO Auto-generated method stub
entityManager.merge(users);// merge:融合
}
@Override
public void deleteUsers(Users users) {
// TODO Auto-generated method stub
Users u = selectUsersByID(users.getUserid());
entityManager.remove(u);// remove:移除
}
@Override
public Users selectUsersByID(Integer userid) {
// TODO Auto-generated method stub
return entityManager.find(Users.class, userid);
}
// HQL的查询方式
@Override
public List<Users> selectUserByName(String username) {
return entityManager.createQuery("from Users where username=?").setParameter(1, username).getResultList();
}
// 普通SQL的查询方式
@Override
public List<Users> selectUserByNameUseSQL(String username) {
return entityManager.createNativeQuery("select * from users where username=?", Users.class)
.setParameter(1, username).getResultList();
}
@Override
public List<Users> selectUserByNameUseCriteria(String username) {
// 通过CriteriaBuilder 创建CriteriaQuery创建查询条件;
CriteriaBuilder builer = entityManager.getCriteriaBuilder();
// CriteriaQuery对象执行查询的Criteria对象
// select * from users
CriteriaQuery<Users> query = builer.createQuery(Users.class);
// 获取要查询实体类的封装对象
// 取对象进行SQL里的列对应
Root<Users> root = query.from(Users.class);
// 封装查询条件
Predicate equal = builer.equal(root.get("username"), username);
query.where(equal);
TypedQuery<Users> typeQuery = entityManager.createQuery(query);
// 执行查询
return typeQuery.getResultList();
}
}
- 测试
package test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.OVA.dao.UserDao;
import com.OVA.pojo.Users;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestDaoImpl {
@Autowired
private UserDao userdao;
Users users = null;
// 添加
@Test
@Transactional
@Rollback(false)
public void testInsert() {
// TODO Auto-generated method stub
users = new Users();
users.setUsername("张宁");
users.setUserage(11);
userdao.insertUsers(users);
}
// 删除
@Test
@Transactional
@Rollback(false)
public void testDelete() {
// TODO Auto-generated method stub
users = new Users();
users.setUserid(5);
userdao.deleteUsers(users);
}
// 查找
@Test
@Transactional
@Rollback(false)
public void testSelect() {
// TODO Auto-generated method stub
System.out.println(userdao.selectUsersByID(4));
}
// 更新
@Test
@Transactional
@Rollback(false)
public void testUpdate() {
// TODO Auto-generated method stub
users = new Users();
users.setUserid(4);
users.setUsername("张宁");
users.setUserage(2);
userdao.updateUsres(users);
}
@Test
@Transactional
@Rollback(false)
public void testSelectByName() {
System.out.println(userdao.selectUserByName("张三"));
}
@Test
@Transactional
@Rollback(false)
public void testSelectByNameUseSQL() {
for (Users users : userdao.selectUserByName("张三")) {
System.out.println(users);
}
}
@Test
@Transactional
@Rollback(false)
public void testSelectByNameUseQBC() {
for (Users users : userdao.selectUserByName("张三")) {
System.out.println(users);
}
}
}
有什么错误欢迎大家批评指正,源码已经放到我的下载里面了。