1.创建项目,导入jar包
这里比spring+hibernate多了个hibernate-entitymanager.5.0.7.jar
2.编写applicationContext.xml
jdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/testhibernate?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
jdbc.driver.class=com.mysql.cj.jdbc.Driver
jdbc.username=root
jdbc.password=200934652qwe
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: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">
<!-- 配置读取properties文件的工具类 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置c3p0连接池 -->
<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"></property>
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- hibernate相关属性注入 -->
<!-- 配置数据库类型 -->
<property name="database" value="MYSQL"></property>
<!-- 配置正向工程 -->
<property name="generateDdl" value="true"></property>
<!-- 显示正在执行的sql -->
<property name="showSql" value="true"></property>
</bean>
</property>
<property name="packagesToScan">
<list>
<value>per.czt.pojo</value>
</list>
</property>
</bean>
<!-- 配置Hibernate-jpa的事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- 配置开启注解事务处理 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 配置springIOC的注解扫描 -->
<context:component-scan base-package="per.czt.dao,per.czt.dao.impl"/>
</beans>
3.编写pojo对象Users
Users.java
package per.czt.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;
@Entity
@Table(name="t_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;
}
public Users() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Users [userid=" + userid + ", username=" + username + ", userage=" + userage + "]";
}
}
4.编写dao层和dao.impl层
UsersDao.java
package per.czt.dao;
import java.util.List;
import per.czt.pojo.Users;
public interface UsersDao {
void insertUsers(Users users);
void deleteUsers(Users users);
void updateUsers(Users users);
Users selectUsersById(Integer userid);
List<Users> selectUsersByName(String name);
List<Users> selectUsersByNameUseSQL(String name);
List<Users> selectUsersByNameUseCriteria(String name);
}
UsersDaoImpl.java
package per.czt.dao.impl;
import java.util.List;
import javax.persistence.*;
import javax.persistence.criteria.*;
import org.springframework.stereotype.Repository;
import per.czt.dao.UsersDao;
import per.czt.pojo.Users;
@Repository
public class UsersDaoImpl implements UsersDao {
@PersistenceContext(name="entityManagerFactory")
private EntityManager entityManager;
@Override
public void insertUsers(Users users) {
// TODO Auto-generated method stub
entityManager.persist(users);
}
@Override
public void deleteUsers(Users users) {
// TODO Auto-generated method stub
entityManager.remove(users);
}
@Override
public void updateUsers(Users users) {
// TODO Auto-generated method stub
entityManager.merge(users);
}
@Override
public Users selectUserById(Integer user_id) {
// TODO Auto-generated method stub
return entityManager.find(Users.class, user_id);
}
@Override
public List<Users> selectUsersByName(String user_name) {
// TODO Auto-generated method stub
return this.entityManager.createQuery("from Users where username=:user_name").setParameter("user_name", user_name).getResultList();
}
@Override
public List<Users> selectUsersByNameUseSQL(String user_name) {
// TODO Auto-generated method stub
Query query=this.entityManager.createNativeQuery("select * from t_users2 where user_name=?", Users.class).setParameter(1,user_name);
return query.getResultList();
}
@Override
public List<Users> selectUsersByNameUseCriteria(String user_name) {
// TODO Auto-generated method stub
//CriteriaBuilder:创建一个CriteriaQuery,创建查询条件
CriteriaBuilder criteriaBuilder=this.entityManager.getCriteriaBuilder();
//CriteriaQuery:执行查询的Criteria对象
//select * from t_users2
CriteriaQuery<Users> criteriaQuery=criteriaBuilder.createQuery(Users.class);
//获取要查询的实体类对象
Root<Users> root=criteriaQuery.from(Users.class);
//封装查询条件
Predicate cate=criteriaBuilder.equal(root.get("username"), user_name);
criteriaQuery.where(cate);
//执行查询
TypedQuery<Users> typeQuery= this.entityManager.createQuery(criteriaQuery);
return typeQuery.getResultList();
}
}
5.这里就不写service层了,直接junit中测试
package per.czt.test;
import java.util.List;
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 per.czt.dao.UsersDao;
import per.czt.pojo.Users;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestUsersDaoImpl {
@Autowired
private UsersDao usersDao;
/*
* @Test
*
* @Transactional
*
* @Rollback(value=false) public void testInsertUsers() { Users users=new
* Users(); users.setUsername("小三"); users.setUserage(19);
* usersDao.insertUsers(users);
*
* }
*
* @Test
*
* @Transactional
*
* @Rollback(value=false) public void testUpdateUsers() { Users users=new
* Users(); users.setUsername("小明"); users.setUserage(21); users.setUserid(3);
* usersDao.updateUsers(users);
*
* }
@Test
public void testSelectUsersById() {
Users users = usersDao.selectUserById(1);
System.out.println(users);
}
@Test
@Transactional
@Rollback(value = false)
public void testDeleteUsers() {
Users user=usersDao.selectUserById(1);
if(user!=null) {
usersDao.deleteUsers(user);
}
}
@Test
public void testSelectUsersByName() {
List<Users> usersList = usersDao.selectUsersByName("xiaoming");
System.out.println(usersList.size());
}
@Test
public void testSelectUsersByNameUseSQL() {
List<Users> usersList = usersDao.selectUsersByNameUseSQL("xiaoming");
System.out.println(usersList.size());
}*/
@Test
public void testSelectUsersByNameUseCriteria() {
List<Users> usersList = usersDao.selectUsersByNameUseSQL("xiaoming");
System.out.println(usersList.size());
}
}