Hibernate with Spring Data JPA
Spring提供的ORM模組挺強大的,在整合這兩個資深模組,不得不說方便很多。然而一般來說我們通常會使用Hibernate與Spring Data JPA做結合,來幫助我們達到程式碼最少化的方式。
在傳統的Hibernate上我們通常需要有一個hibernate.cfg.xml指定相關的物件,爾後使用EntityManager進行操作。但若使用Spring操作Hibernate是不需要使用hibernate.cfg.xml的,可以直接與Spring等設定檔寫在一起,基本上Spring會自行去做IOC、DI等動作,將Hibernate完成初始設定,後續再搭配Spring Data JPA去做DB的操作,到這邊基本上我們沒有在控管DB了,若要控管我們可以使用AOP去攔截做些特定的事情。
POM
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.3.RELEASE</version>
</dependency>
<!-- DBCP -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.0</version>
</dependency>
Hibernate Config
在Spring版本3以後,是有提供JavaConfig的方式,不需要再去設定xml造成檔案控管的不方便,那麼我個人也是喜歡JavaConfig的方式,因此這邊也將使用JavaConfig方式進行說明,若要使用xml,其實也大同小異。
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = {"com.jmeter.example.dao"})
public class HibernateConfig {
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
bean.setDataSource(dataSource());
bean.setPackagesToScan(new String[] { "com.jmeter.example.entity" });
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setShowSql(true);
vendorAdapter.setDatabasePlatform("org.hibernate.dialect.SQLServerDialect");
vendorAdapter.setDatabase(Database.SQL_SERVER);
bean.setJpaVendorAdapter(vendorAdapter);
return bean;
}
@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
dataSource.setUrl("jdbc:sqlserver://localhost;databaseName=andy");
dataSource.setUsername("admin");
dataSource.setPassword("admin@andy");
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public JdbcTemplate jdbcTemplate(){
return new JdbcTemplate(dataSource());
}
@Bean
public HibernateExceptionTranslator hibernateExceptionTranslator(){
return new HibernateExceptionTranslator();
}
}
User Entity
Entity主要依照JPA格式為主,在使用Hibernate一定要有ID,若沒有則會有出現錯誤。
@Entity
@Table(name="USERS")
public class User {
@Id
@Column(name="USER_ID")
private String id;
@Column(name="USER_NAME")
private String userName;
@Column(name="PASSWORD")
private String password;
@Column(name="NICK_NAME")
private String nickName;
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the userName
*/
public String getUserName() {
return userName;
}
/**
* @param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the nickName
*/
public String getNickName() {
return nickName;
}
/**
* @param nickName the nickName to set
*/
public void setNickName(String nickName) {
this.nickName = nickName;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", nickName=" + nickName + "]";
}
}
User Dao
JpaRepository是屬於Spring Data JPA的介面,基本上我們只要繼承這個介面,不需要控制連線以及實作簡單的CRUD,若物件有關聯的問題,可以直接在Entity設定即可,這邊我將後續作介紹。
@Repository
public interface UserDao extends JpaRepository<User, String>{
}