Spring教程-Spring Data JPA 教程
Spring Data JPA API 提供了 JpaTemplate 类,用于将 Spring 应用程序与 JPA 进行整合。
JPA(Java 持久化 API)是用于在企业应用程序中持久化对象的 Sun 规范。它目前被用作复杂实体 bean 的替代品。
JPA 规范的实现由许多供应商提供,如:
- Hibernate
- Toplink
- iBatis
- OpenJPA 等。
Spring JpaTemplate 的优势
您无需编写持久化、更新、删除或搜索对象的前后代码,如创建 Persistence 实例、创建 EntityManagerFactory 实例、创建 EntityTransaction 实例、创建 EntityManager 实例、提交 EntityTransaction 实例和关闭 EntityManager。
因此,它节省了大量的代码。
在这个例子中,我们将使用 Hibernate 来实现 JPA。
Spring 和 JPA 整合示例
让我们看一下将 Spring 应用程序与 JPA 集成的简单步骤:
- 创建 Account.java 文件
- 创建 Account.xml 文件
- 创建 AccountDao.java 文件
- 创建 persistence.xml 文件
- 创建 applicationContext.xml 文件
- 创建 AccountsClient.java 文件
在这个例子中,我们将集成 Hibernate 应用程序与 Spring。让我们看一下 JPA 示例与 Spring 的目录结构
1) Account.java
这是一个简单的 POJO 类。
package cn.javatiku;
public class Account {
private int accountNumber;
private String owner;
private double balance;
//no-arg and parameterized constructor
//getters and setters
}
2) Account.xml
此映射文件包含持久类的所有信息。
<entity-mappings version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
http://java.sun.com/xml/ns/persistence/orm_1_0.xsd ">
<entity class="cn.javatiku.Account">
<table name="account100"></table>
<attributes>
<id name="accountNumber">
<column name="accountnumber"/>
</id>
<basic name="owner">
<column name="owner"/>
</basic>
<basic name="balance">
<column name="balance"/>
</basic>
</attributes>
</entity>
</entity-mappings>
3) AccountDao.java
package cn.javatiku;
import java.util.List;
import org.springframework.orm.jpa.JpaTemplate;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public class AccountsDao{
JpaTemplate template;
public void setTemplate(JpaTemplate template) {
this.template = template;
}
public void createAccount(int accountNumber,String owner,double balance){
Account account = new Account(accountNumber,owner,balance);
template.persist(account);
}
public void updateBalance(int accountNumber,double newBalance){
Account account = template.find(Account.class, accountNumber);
if(account != null){
account.setBalance(newBalance);
}
template.merge(account);
}
public void deleteAccount(int accountNumber){
Account account = template.find(Account.class, accountNumber);
if(account != null)
template.remove(account);
}
public List<Account> getAllAccounts(){
List<Account> accounts =template.find("select acc from Account acc");
return accounts;
}
}
4) persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
<persistence-unit name="ForAccountsDB">
<mapping-file>cn/javatiku/Account.xml</mapping-file>
<class>cn.javatiku.Account</class>
</persistence-unit>
</persistence>
5) 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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<tx:annotation-driven transaction-manager="jpaTxnManagerBean" proxy-target-class="true"/>
<bean id="dataSourceBean" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property>
<property name="username" value="system"></property>
<property name="password" value="oracle"></property>
</bean>
<bean id="hbAdapterBean" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"></property>
<property name="generateDdl" value="true"></property>
<property name="databasePlatform" value="org.hibernate.dialect.OracleDialect"></property>
</bean>
<bean id="emfBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSourceBean"></property>
<property name="jpaVendorAdapter" ref="hbAdapterBean"></property>
</bean>
<bean id="jpaTemplateBean" class="org.springframework.orm.jpa.JpaTemplate">
<property name="entityManagerFactory" ref="emfBean"></property>
</bean>
<bean id="accountsDaoBean" class="cn.javatiku.AccountsDao">
<property name="template" ref="jpaTemplateBean"></property>
</bean>
<bean id="jpaTxnManagerBean" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emfBean"></property>
</bean>
</beans>
属性 generateDdl 会自动创建表。
属性 showSql 会在控制台上显示 SQL 查询。
6) AccountsClient.java
package cn.javatiku;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class AccountsClient{
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountsDao accountsDao = context.getBean("accountsDaoBean",AccountsDao.class);
accountsDao.createAccount(15, "Jai Kumar", 41000);
accountsDao.createAccount(20, "Rishi ", 35000);
System.out.println("Accounts created");
//accountsDao.updateBalance(20, 50000);
//System.out.println("Account balance updated");
/*List<Account> accounts = accountsDao.getAllAccounts();
for (int i = 0; i < accounts.size(); i++) {
Account acc = accounts.get(i);
System.out.println(acc.getAccountNumber() + " : " + acc.getOwner() + " (" + acc.getBalance() + ")");
}*/
//accountsDao.deleteAccount(111);
//System.out.println("Account deleted");
}
}
输出
Hibernate: insert into account100 (balance, owner, accountnumber) values (?, ?, ?)
Hibernate: insert into account100 (balance, owner, accountnumber) values (?, ?, ?)
Accounts created