整合Spring與Hibernate

在學習spring的時候,要整合hibernate,原本是看起來挺簡單的,可是遇到的遠要比想到了多,並且多不少,
期間幾天一個bug實在難調,幾度放棄,但終究柳暗花明,抑制不住喜悅就想着分享一下成果吧。

一、實體類 User:java

 1 import java.util.Date;
 2 
 3 import javax.persistence.Column;
 4 import javax.persistence.Entity;
 5 import javax.persistence.GeneratedValue;
 6 import javax.persistence.GenerationType;
 7 import javax.persistence.Id;
 8 import javax.persistence.Temporal;
 9 import javax.persistence.TemporalType;
10 
11 @Entity
12 public class User {
13 
14     @Id
15     @Column(name="user_id")
16     @GeneratedValue(strategy=GenerationType.IDENTITY)
17     private Integer id;
18     @Column(name="user_name")
19     private String name;
20     private String pass;
21     @Temporal(TemporalType.DATE)
22     private Date birth;
23     
24     
25     
26     public User() {
27         
28     }
29     
30     
31     public User( String name, String pass, Date birth) {
32         super();
33         this.name = name;
34         this.pass = pass;
35         this.birth = birth;
36     }
37     
38     public Integer getId() {
39         return id;
40     }
41 
42 
43     public void setId(Integer id) {
44         this.id = id;
45     }
46 
47 
48     public String getName() {
49         return name;
50     }
51     public void setName(String name) {
52         this.name = name;
53     }
54     public String getPass() {
55         return pass;
56     }
57     public void setPass(String pass) {
58         this.pass = pass;
59     }
60 
61 
62     public Date getBirth() {
63         return birth;
64     }
65 
66 
67     public void setBirth(Date birth) {
68         this.birth = birth;
69     }
70     
71     
72 }

 



二、hibernate配置文件hibernate.cfg.xml:mysql

 1 <?xml version='1.0' encoding='utf-8'?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 5 
 6 <hibernate-configuration>
 7 
 8     <session-factory>
 9         <!-- hibernate 所需的配置信息 -->
10         <property name="show_sql">true</property>
11         <property name="dialect">org.hibernate.dialect.MySQLDialect</property><!--方言-->
12         <property name="format_sql">true</property>
13         <property name="hbm2ddl.auto">update</property>
14         
15         <!-- hibernate 指定映射類 -->
16         <mapping class="com.csu.domain.User"/>
17         
18     </session-factory>
19     
20 </hibernate-configuration>

 



三、c3p0數據庫鏈接池所須要的數據庫配置信息,放置在jdbc.properties文件中,這樣也方便往後修改只須要改動屬性文件,
而不須要改動配置文件:

spring

user=root
password=7890
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/spring
maxPoolSize=200
minPoolSize=2
initialPoolSize=2

 



四、spring的配置文件beans.xml:

sql

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 
 3 <!-- 整個Spring 文件的根元素就是beans -->
 4 <beans xmlns="http://www.springframework.org/schema/beans"
 5 xmlns:p="http://www.springframework.org/schema/p"
 6 xmlns:util="http://www.springframework.org/schema/util"
 7 xmlns:context="http://www.springframework.org/schema/context"
 8     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 9     xsi:schemaLocation="http://www.springframework.org/schema/beans
10         http://www.springframework.org/schema/beans/spring-beans.xsd
11         
12         http://www.springframework.org/schema/util
13         http://www.springframework.org/schema/util/spring-util.xsd
14         
15         http://www.springframework.org/schema/context
16         http://www.springframework.org/schema/context/spring-context.xsd
17         ">
18 
19        <!-- *****************配置數據源*********************** -->
20       
21        <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
22        
23            <property name="locations">
24                <!-- 列出須要讀取的屬性文件 -->
25                <list>
26                    <value>classpath:jdbc.properties</value>
27                </list>
28            </property>
29                
30        </bean>
31            
32        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
33            p:user="${user}"
34            p:password="${password}"
35            p:driverClass="${driverClass}"
36            p:jdbcUrl="${jdbcUrl}"
37            p:maxPoolSize="${maxPoolSize}"
38            p:minPoolSize="${minPoolSize}"
39            p:initialPoolSize="${initialPoolSize}"
40        />
41        <!-- *****************配置數據源*********************** -->
42     
43     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
44     p:dataSource-ref="dataSource"
45     p:configLocation="classpath:hibernate.cfg.xml"
46     />
47     <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"
48     p:sessionFactory-ref="sessionFactory"
49     />
50         
51 </beans>

 


五、測試主類:數據庫

 1 import java.util.Date;
 2 
 3 import org.hibernate.FlushMode;
 4 import org.springframework.context.ApplicationContext;
 5 import org.springframework.context.support.ClassPathXmlApplicationContext;
 6 import org.springframework.orm.hibernate3.HibernateTemplate;
 7 
 8 import com.csu.domain.User;
 9 
10 public class SpHiTest {
11 
12     public static void main(String[] args) {
13         ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
14 
15         //直接利用數據庫的HibernateTemplate類進行數據庫操做,能夠極大方便了操做流程
16         HibernateTemplate ht = (HibernateTemplate)ctx.getBean("hibernateTemplate");
17 
18         ht.save(new User("chen","123",new Date()));        
19         
20     }
21 
22     
23 
24 }

 

六、期間碰到的問題是一直出現這個問題:session

 
Exception in thread "main" org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
    at org.springframework.orm.hibernate4.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1128)
    at org.springframework.orm.hibernate4.HibernateTemplate$20.doInHibernate(HibernateTemplate.java:737)
    at org.springframework.orm.hibernate4.HibernateTemplate.doExecute(HibernateTemplate.java:341)
    at org.springframework.orm.hibernate4.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:309)
    at org.springframework.orm.hibernate4.HibernateTemplate.persist(HibernateTemplate.java:734)
    at com.csu.test.SpHiTest.main(SpHiTest.java:26)
 

 


反正不管怎麼調都沒法正確,最終仍是將hibernate4版本換成了hibernate3才得以解決。最後的結果看一下:

相關文章
相關標籤/搜索