JPA:Java持久层API,由Sun公司提供了一套对于持久层操作的标准
Hibernate:Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架。
Hibernate JPA:是在Hibernate3.2版本中提供了对于JPA标准的实现,提供了一套按照JPA标准来实现持久层开发的API。
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>4.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>4.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>4.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>4.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>4.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-ormartifactId>
<version>4.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>4.2.5.RELEASEversion>
<scope>testscope>
dependency>
<dependency>
<groupId>org.hibernategroupId>
<artifactId>hibernate-coreartifactId>
<version>4.3.11.Finalversion>
dependency>
<dependency>
<groupId>org.hibernategroupId>
<artifactId>hibernate-entitymanagerartifactId>
<version>4.3.11.Finalversion>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.38version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.10version>
dependency>
dependencies>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
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.2.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.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" value="${jdbc.driver.class}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
bean>
<bean id="entityManager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource">property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL">property>
<property name="generateDdl" value="true">property>
<property name="showSql" value="true">property>
bean>
property>
<property name="packagesToScan">
<list>
<value>cn.gotojava.pojovalue>
list>
property>
bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManager"/>
bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:component-scan base-package="cn.gotojava"/>
beans>
# 数据库URL
jdbc.url=jdbc:mysql://localhost:3306/yunhome?&useUnicode=true&characterEncoding=utf-8&autoReconnect=true
# 数据库驱动类
jdbc.driver.class=com.mysql.jdbc.Driver
# 数据库连接用户名
jdbc.username=root
# 数据库连接密码
jdbc.password=root
// 表示该类是一个实体类
@Entity
// 实体与数据库中的表进行映射,如果数据表不存在,则通过正向工程创建数据表
@Table(name = "t_users")
public class Users implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1459398903271506845L;
// 表示该属性为主键
@Id
// 主键生成策略:GenerationType.IDENTITY表示自动增长列
@GeneratedValue(strategy = GenerationType.IDENTITY)
// 表示该属性和数据表中的"id"进行映射,如果该属性不存在,则可以通过正向工程进行生成
@Column(name = "id")
private Integer id; // 编号
@Column(name = "name")
private String name; // 姓名
@Column(name = "age")
private Integer age; // 年龄
@Column(name = "address")
private String address; // 地址
@Column(name = "phone")
private String phone; // 手机号
public Users() {
super();
}
public Users(Integer id) {
super();
this.id = id;
}
public Users(String name, Integer age, String address, String phone) {
super();
this.name = name;
this.age = age;
this.address = address;
this.phone = phone;
}
public Users(Integer id, String name, Integer age, String address, String phone) {
super();
this.id = id;
this.name = name;
this.age = age;
this.address = address;
this.phone = phone;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Users [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + ", phone=" + phone
+ "]";
}
}
public interface IUsersDao {
/**
* 新增用户数据家
* @param user 封装好的数据对象
*/
void saveUsers(Users user);
/**
* 根据用户编号删除用户数据
* @param userId 用户编号
*/
void deleteUsers(Users user);
/**
* 修改用户信息
* @param user 封装好的数据对象
*/
void updateUsers(Users user);
/**
* 根据用户编号查询用户数据
* @param userId 用户编号
* @return 返回对于用户编号的用户信息
*/
Users findUsersByUsersId(Integer userId);
}
// 持久层注解
@Repository
// 事务注解,用于管理事务操作
@Transactional
public class UsersDaoImpl implements IUsersDao {
@PersistenceContext(name = "entityManager")
private EntityManager entityManager;
@Override
public void saveUsers(Users user) {
this.entityManager.persist(user);
}
@Override
public void deleteUsers(Users user) {
Users userObj = this.findUsersByUsersId(user.getId());
this.entityManager.remove(userObj);
}
@Override
public void updateUsers(Users user) {
this.entityManager.merge(user);
}
@Override
public Users findUsersByUsersId(Integer userId) {
return this.entityManager.find(Users.class, userId);
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class UsersDaoImplTest {
@Autowired
private IUsersDao userDao;
/**
* 测试新增方法
*/
@Test
public void testSaveUsers() {
Users user = new Users("德玛西亚", 123, "中国北京", "123456");
this.userDao.saveUsers(user);
}
/**
* 测试删除方法
*/
@Test
public void testDeleteUsers() {
this.userDao.deleteUsers(new Users(5));
}
/**
* 测试更新方法
*/
@Test
public void testUpdateUsers() {
Users user = new Users(6,"后裔射日", 125, "中国北京", "123456");
this.userDao.updateUsers(user);
}
/**
* 根据用户编号查询用户信息
*/
@Test
public void testFindUsersByUsersId() {
Users user = this.userDao.findUsersByUsersId(3);
System.out.println(user);
}
}
/**
* 根据名字查询用户信息
* @param name 用户姓名
* @return 返回一个包含指定姓名的用户列表
*/
List<Users> findUserByName(String name);
@Override
public List<Users> findUserByName(String name) {
// 编写查询条件
Query hqlQuery = this.entityManager.createQuery("FROM Users WHERE name = :name");
// 设置查询参数
Query query = hqlQuery.setParameter("name", name);
// 返回查询结果
return query.getResultList();
}
/**
* 根据用户名查询用户信息,使用HQL
*/
@Test
public void testFindUserByName() {
List<Users> userObj = this.userDao.findUserByName("张三");
for (Users users : userObj) {
System.out.println(users);
}
}
/**
* 根据名字模糊查询用户信息
* @param name 用户姓名
* @return 返回一个包含符合姓名范围的用户列表
*/
List<Users> findUserByLikeName(String name);
@Override
public List<Users> findUserByLikeName(String name) {
// 编写SQL查询条件
Query sqlQuery = this.entityManager.createNativeQuery("SELECT * FROM t_users WHERE name LIKE :name", Users.class);
// 设置查询参数
Query query = sqlQuery.setParameter("name", "%"+name+"%");
// 返回查询结果
return query.getResultList();
}
/**
* 根据用户名查询用户信息,使用SQL
*/
@Test
public void testFindUserByLikeName() {
List<Users> users = this.userDao.findUserByLikeName("张");
for (Users user : users) {
System.out.println(user);
}
}