SpringData【Spring 整合 HibernateJPA】(1)
<version>4.3.21.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.7.Final</version>
</dependency>
</dependencies>
3.添加配置文件
jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
jdbc.driver.class=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=123456
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.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>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL"/>
<property name="generateDdl" value="true"/>
<property name="showSql" value="true"/>
</bean>
</property>
<property name="packagesToScan">
<list>
<value>com.dpb.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"/>
<context:component-scan base-package="com.dpb"/>
</beans>
4.添加 pojo
/**
@program: spring-hibernate-jpa
@description: Users 的 Pojo 对象
@author: 波波烤鸭
@create: 2019-05-18 09:37
*/
@Entity
@Table(name="users")
public class Users implements Serializable {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)//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 String toString() {
return "Users [userid=" + userid + ", username=" + username + ", userage=" + userage + "]";
}
}
5.Dao 接口和实现
/**
定义接口中的方法
*/
public interface UserDao {
void insertUsers(Users users);
void updateUsers(Users users);
void deleteUsers(Users users);
Users selectUsersById(Integer userid);
Lis
t<Users> selectUserByName(String username);
List<Users> selectUserByNameUseSQL(String username);
List<Users> selectUserByNameUseCriteria(String username);
}
import org.springframework.stereotype.Repository;
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 java.util.List;
/**
@program: spring-hibernate
@description: 用户持久层的实现类
@author: 波波烤鸭
@create: 2019-05-18 09:43
*/
@Repository
public class UserDaoImpl implements UserDao {
@PersistenceContext(name="entityManagerFactory")
private EntityManager entityManager;
@Override
public void insertUsers(Users users) {
this.entityManager.persist(users);
}
@Override
public void updateUsers(Users users) {
this.entityManager.merge(users);
}
@Override
public void deleteUsers(Users users) {
Users u = this.selectUsersById(users.getUserid());
this.entityManager.remove(u);
}
@Override
public Users selectUsersById(Integer userid) {
return this.entityManager.find(Users.class, userid);
}
@Override
public List<Users> selectUserByName(String username) {
return this.entityManager.createQuery(" from Users where username = :abc").setParameter("abc", username).getResultList();
}
@Override
public List<Users> selectUserByNameUseSQL(String username) {
//在 Hibernate JPA 中 如果通过?方式来帮顶参数,那么他的查数是从 1 开始的。而 hibernate 中是从 0 开始的。
return this.entityManager.createNativeQuery("select * from t_users where username = ?", Users.class).setParameter(1, username).getResultList();
}
@Override
public List<Users> selectUserByNameUseCriteria(String username) {
//CriteriaBuilder 对象:创建一个 CriteriaQuery,创建查询条件。
CriteriaBuilder builber = this.entityManager.getCriteriaBuilder();
//CriteriaQuery 对象:执行查询的 Criteria 对象
//select * from t_users
CriteriaQuery<Users> query = builber.createQuery(Users.class);
//获取要查询的实体类的对象
Root<Users> root = query.from(Users.class);
//封装查询条件
Predicate cate = builber.equal(root.get("username"), username);
//select * from t_users where username = 张三
query.where(cate);
//执行查询
TypedQuery<Users> typeQuery = this.entityManager.createQuery(query);
return typeQuery.getResultList();
}
}
6.单元测试
/**
@program: spring-hibernate
@description: 单元测试
@author: 波波烤鸭
@create: 2019-05-18 09:48
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestDemo {
@Autowired
private UserDao usersDao;
/**
添加用户
*/
@Test
@Transactional// 在测试类对于事务提交方式默认的是回滚。
@Rollback(false)//取消自动回滚
public void testInsertUsers(){
Users users = new Users();
users.setUserage(20);
users.setUsername("张三-jpa");
this.usersDao.insertUsers(users);
}
/**
更新用户
*/
@Test
@Transactional
@Rollback(false)
public void testUpdateUsers(){
Users users = new Users();
users.setUserid(2);
users.setUserage(22);
users.setUsername("李四");
评论