在Spring框架下配置JPA

1,MyEclipse8.5新建一個Java Web工程,我這裏命名爲JpaSpring。在左側的Package Explorer裏面,工程名JpaSpring上鼠標右鍵 -> MyEclipse ->Add Spring Capabilities,彈出如下對話框


Spring version選擇默認的Spring 3.0。中間的多選框勾選項如上圖。點擊Finish完成Spring的配置。會發現在工程的src包下已經自動生成了applicationContext.xml應用程序上下文文件。

然後同樣在左側的Package Explorer裏面,工程名JpaSpring上鼠標右鍵 -> MyEclipse ->Add JPA Capabilities,彈出如下對話框

由於是先添加了Spring的各個支持庫,所以這裏默認已經有Spring的支持了,直接點擊Next就可以後,如下圖:



這和上一篇日誌見到的界面一樣,不再贅述,仍然點擊Next後,如下圖:



點擊Finish完成配置。此時就會發現在src/META-INF路徑下自動生成了persistence.xml。同時applicationContext.xml文件中自動添加了兩個id名別爲entityManagerFactory和transactionManager的bean。

然後要做的是把applicationContext.xml文件拖入src/MET-INF路徑下,也就是和persistence.xml放在一起。最後的包結構如下圖:



和上一篇日誌差不多,domain下的Test_Account.java是對應於表test_account的持久化類,dao下的Test_AccountDAO.java是數據訪問類,test下的TestResult.java是包含主函數的測試類。

持久化類Test_Account.java的代碼如下:
import ...........;

@Entity
@Table(name="test_account")
public class Test_Account implements Serializable {

@Id
private String account;
private String password;
private double balance;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}

數據訪問類Test_AccountDAO.java代碼如下:
import .......;

public class Test_AccountDAO extends JpaDaoSupport {

public void save(Test_Account customer) { //插入
this.getJpaTemplate().persist(customer);
}
public void update(Test_Account customer) { //更新
this.getJpaTemplate().merge(customer);
}

public void remove(Test_Account customer){ //刪除

JpaTemplate t = this.getJpaTemplate();
t.remove(t.contains(customer) ? customer : t.merge(customer));
//首先判斷要刪除的對象是否是受控狀態,如果不是,則通過merge的返回值,從遊離狀態轉換成受控狀態

//這裏更新時間2011-5-26 

}

//按照主鍵查找一個記錄
public Test_Account findByKey(String account) {
List list=(List)getJpaTemplate().find("select c from Test_Account c where c.account = ?1",account); 
if(list==null||list.size()==0)return null;
Test_Account temp=(Test_Account)list.get(0);
return temp;
}
//查找所有記錄
public List findAllItems()
{
List list =(List)getJpaTemplate().find("select c from Test_Account c"); 
if(list==null||list.size()==0)return null;
return list;
}

public List getQueryResult(double below,String password)
{
List list =(List)getJpaTemplate().find("select c from Test_Account c where c.balance>?1 and c.password=?2",below,password); 
if(list==null||list.size()==0)return null;
return list;
}
//查找所有的賬戶名
public List findAllAccountname()
{ //這種查詢提取只能提取一個屬性構成list,比如這裏提取兩個屬性就會報錯
List list=(List)getJpaTemplate().find("select c.account from Test_Account c"); 
if(list==null||list.size()==0)return null;
return list;
}
}

測試類TestResult.java代碼如下:
import ........;

public class TestResult {


private ClassPathXmlApplicationContext getApplicationContext(){
ClassPathXmlApplicationContext applicationContext=new
ClassPathXmlApplicationContext("META-INF/applicationContext.xml");
return applicationContext;
}

public static void main(String[] args) {
ApplicationContext b=new TestResult().getApplicationContext();
final Test_AccountDAO dao=(Test_AccountDAO)b.getBean("test_accountdao");
Test_Account abc=new Test_Account();
abc.setAccount("hellopeter");
abc.setPassword("jisuanji");
abc.setBalance(2010);
final Test_Account forinsert=abc;

Test_Account med=dao.findByKey("22368");
med.setPassword("bbbbb");
final Test_Account forupdae=med;

TransactionTemplate transactionTemplate=(TransactionTemplate)b.getBean("transactionTemplate");
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
try {
dao.save(forinsert);//插入
dao.update(forupdae);//更新

Test_Account fordelete=dao.findByKey("delete12");
dao.remove(fordelete); //刪除

} catch (Exception e) {
e.printStackTrace();
status.setRollbackOnly();
}
}
});
System.out.println("###############################################");
//查詢不必放在上面的事務模板裏
List allaccountname=dao.findAllAccountname();
for(int i=0;i<allaccountname.size();i++)
{
System.out.println(allaccountname.get(i).toString());
}
System.out.println("###############################################");
List list=dao.findAllItems();
for(int i=0;i<list.size();i++)
{
Test_Account rr=(Test_Account)list.get(i);
System.out.println(rr.getAccount()+" "+rr.getPassword()+" "+rr.getBalance());
}
System.out.println("################################################");
List queryresult=dao.getQueryResult(1000,"jisuanji");//查詢餘額大於1000,且密碼爲jisuanji的賬戶
for(int i=0;i<queryresult.size();i++)
{
Test_Account rr=(Test_Account)queryresult.get(i);
System.out.println(rr.getAccount()+" "+rr.getPassword()+" "+rr.getBalance());
}
}

}

持久化配置文件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="JPASpringPU" transaction-type="RESOURCE_LOCAL">
<provider>oracle.toplink.essentials.PersistenceProvider</provider>

<class>domain.Test_Account</class><!-- 自己添加的持久化類 -->

<properties>
<property name = "toplink.jdbc.driver" value = "com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name = "toplink.jdbc.url" value = "jdbc:sqlserver://localhost:1433;DatabaseName=TestDB"/>
<property name = "toplink.jdbc.user" value = "sa"/>
<property name = "toplink.jdbc.password" value = "1234"/>
</properties>
</persistence-unit>

</persistence>

應用程序上下文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:p="http://www.springframework.org/schema/p"
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.xsd" xmlns:tx="http://www.springframework.org/schema/tx">


<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="JPASpringPU" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<!-- <property name="jpaDialect" ref="jpaDialect" /> -->
</bean>


<!-- 上面是自動生成的,下面的2個bean是自己添加的////////////////////////////////////////////////////////////// -->
<bean id="test_accountdao" class="dao.Test_AccountDAO"> <!-- 自己寫的dao數據訪問類 -->
<property name="entityManagerFactory" ref="entityManagerFactory" />
<!-- 這兒不加這個property執行時會報錯,提示加上 -->
</bean>

<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager" />
<!-- 這兒不加這個property執行時會報錯,提示加上 -->
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />

</beans>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章