Hibernate中使用Spring Data JPA
一、配置文件的方式
1、pom.xml中引入相关依赖
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <!-- Spring data jpa依赖 --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.11.4.RELEASE</version> </dependency> <!-- hibernate依赖 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.1.7.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>5.1.7.Final</version> </dependency> <!-- mysql依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.42</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies>
2、JPA配置MATE-INF/persistence.xml
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> <persistence-unit name="myjpa" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <class>com.wyl.bean.User</class> <properties> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/test"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="root"/> <property name=" hibernate.show_sql" value="true"/> <property name="hibernate.hbm2ddl.auto" value="update"/> </properties> </persistence-unit> </persistence>
3、创建实体对象User.class
package com.wyl.bean; 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="users") public class User { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; @Column private String userName; @Column private String phone; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Override public String toString() { // TODO Auto-generated method stub return super.toString(); } }
4、创建测试类
package com.wyl;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.Test;
import com.wyl.bean.User;
public class JpaTest {
private EntityManagerFactory factory = Persistence.createEntityManagerFactory("myjpa");
@Test
public void testAdd(){
EntityManager em = factory.createEntityManager();
User user = new User();
user.setUserName("wang");
user.setPhone("123422222222");
em.getTransaction().begin(); //事务开启
try {
em.persist(user); //持久化数据
em.getTransaction().commit(); //事务提交
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
em.getTransaction().rollback(); //事务回滚
} finally {
em.close(); //关闭em
}
}
@Test
public void testFind(){
EntityManager em = factory.createEntityManager();
User user = em.find(User.class, 1);
System.out.println(user.getUserName());
em.getTransaction().begin(); //事务开启
try {
em.merge(user);
em.getTransaction().commit(); //事务提交
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
em.getTransaction().rollback(); //事务回滚
} finally {
em.close(); //关闭em
}
}
@Test
public void testDelete(){
EntityManager em = factory.createEntityManager();
User user = em.find(User.class, 1); //查询到实体
em.getTransaction().begin(); //事务开启
try {
em.remove(user); //删除实体
em.getTransaction().commit(); //事务提交
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
em.getTransaction().rollback(); //事务回滚
} finally {
em.close(); //关闭em
}
}
}
二、配置类的方式
实现步骤:
1、加入Spring data jpa的依赖
2、加入数据库驱动依赖
3、加入jpa实现的依赖(hibernate)
4、定义Entity
5、在spring容器中,定义三个Bean( DataSource、EntityManagerFactory、PlatformTransactionManager)
6、定义Repository
7、操作
1、引入相关依赖
<!-- spring-data-jpa依赖 --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.11.4.RELEASE</version> </dependency> <!-- mysql依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.42</version> </dependency> <!-- hibernate依赖 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.1.7.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>5.1.7.Final</version> </dependency>
2、创建实体类
同上面一样
3、jpa配置类
import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import com.mysql.jdbc.jdbc2.optional.MysqlDataSource; /* * 配置类,相当于spring中的xml文件 * */ @Configuration public class JPAConfiguration { /* *配置数据源 */ @Bean public DataSource createDataSource(){ MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setURL("jdbc:mysql://127.0.0.1:3306/test"); dataSource.setUser("root"); dataSource.setPassword("root"); return dataSource; } /* * 配置EntityManager */ @Bean("entityManagerFactory") public EntityManagerFactory createEntityManager(DataSource dataSource){ LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource); //配置数据源 HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter(); jpaVendorAdapter.setGenerateDdl(true); jpaVendorAdapter.setShowSql(true); em.setPackagesToScan("com.wyl.bean");//设置实体类的扫描路径 em.setJpaVendorAdapter(jpaVendorAdapter); //配置jpa的适配器 em.afterPropertiesSet(); return em.getObject(); } /* * 定义一个事务 */ @Bean("transactionManager") public PlatformTransactionManager createPlatformTransactionManager(EntityManagerFactory emf){ JpaTransactionManager tm = new JpaTransactionManager(); tm.setEntityManagerFactory(emf); return tm; } }
4、创建数据库操作接口
import org.springframework.data.repository.CrudRepository; import com.wyl.bean.User; public interface UserRepository extends CrudRepository<User, Integer> { }
定义Repository的方法:
方法一:继承接口:Repository、CrudRepository、PagingAndSortingRepository、 JpaRepository
方法二:使用@RepositoryDefinition注解
不生成Repository的实现类,使用@NoRepositoryBean注解。
5、测试
import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import com.wyl.bean.User; import com.wyl.jpa.UserRepository; @ComponentScan @EnableJpaRepositories public class App { public static void main( String[] args ) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class); UserRepository repository = context.getBean(UserRepository.class);
User user = new User(); user.setPhone("10086"); user.setUserName("shaya");
repository.save(user);
context.close();
} }