關(guān)于spring和hibernate的使用以及特征等等,在此不再啰嗦,相信大家也都知道,或者去搜索一下即可。
本篇博文的內(nèi)容主要是我最近整理的關(guān)于spring4.x 和 hibernate 4.x 相關(guān)配置和使用方式,當(dāng)然spring3.x以及hibernate4.x也可以借鑒。
首先是配置文件 web.xml 增加以下代碼即可
<!-- 加載spring相關(guān)的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/applicationContext.xml</param-value> </context-param> <!-- 啟用spring監(jiān)聽(tīng) --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
然后建立 applicationContext.xml 文件 ,src下。 文件內(nèi)容如下,注釋我盡量寫(xiě)的很詳細(xì)
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd"> <!-- 引入properties文件 --> <context:property-placeholder location="classpath*:/appConfig.properties" /> <!-- 定義數(shù)據(jù)庫(kù)連接池?cái)?shù)據(jù)源bean destroy-method="close"的作用是當(dāng)數(shù)據(jù)庫(kù)連接不使用的時(shí)候,就把該連接重新放到數(shù)據(jù)池中,方便下次使用調(diào)用 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <!-- 設(shè)置JDBC驅(qū)動(dòng)名稱 --> <property name="driverClass" value="${jdbc.driver}" /> <!-- 設(shè)置JDBC連接URL --> <property name="jdbcUrl" value="${jdbc.url}" /> <!-- 設(shè)置數(shù)據(jù)庫(kù)用戶名 --> <property name="user" value="${jdbc.username}" /> <!-- 設(shè)置數(shù)據(jù)庫(kù)密碼 --> <property name="password" value="${jdbc.password}" /> <!-- 設(shè)置連接池初始值 --> <property name="initialPoolSize" value="5" /> </bean> <!-- 配置sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <!-- 數(shù)據(jù)源 --> <property name="dataSource" ref="dataSource" /> <!-- hibernate的相關(guān)屬性配置 --> <property name="hibernateProperties"> <value> <!-- 設(shè)置數(shù)據(jù)庫(kù)方言 --> hibernate.dialect=org.hibernate.dialect.MySQLDialect <!-- 設(shè)置自動(dòng)創(chuàng)建|更新|驗(yàn)證數(shù)據(jù)庫(kù)表結(jié)構(gòu) --> hibernate.hbm2ddl.auto=update <!-- 是否在控制臺(tái)顯示sql --> hibernate.show_sql=true <!-- 是否格式化sql,優(yōu)化顯示 --> hibernate.format_sql=true <!-- 是否開(kāi)啟二級(jí)緩存 --> hibernate.cache.use_second_level_cache=false <!-- 是否開(kāi)啟查詢緩存 --> hibernate.cache.use_query_cache=false <!-- 數(shù)據(jù)庫(kù)批量查詢最大數(shù) --> hibernate.jdbc.fetch_size=50 <!-- 數(shù)據(jù)庫(kù)批量更新、添加、刪除操作最大數(shù) --> hibernate.jdbc.batch_size=50 <!-- 是否自動(dòng)提交事務(wù) --> hibernate.connection.autocommit=true <!-- 指定hibernate在何時(shí)釋放JDBC連接 --> hibernate.connection.release_mode=auto <!-- 創(chuàng)建session方式 hibernate4.x 的方式 --> hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext <!-- javax.persistence.validation.mode默認(rèn)情況下是auto的,就是說(shuō)如果不設(shè)置的話它是會(huì)自動(dòng)去你的classpath下面找一個(gè)bean-validation**包 所以把它設(shè)置為none即可 --> javax.persistence.validation.mode=none </value> </property> <!-- 自動(dòng)掃描實(shí)體對(duì)象 tdxy.bean的包結(jié)構(gòu)中存放實(shí)體類 --> <property name="packagesToScan" value="tdxy.bean" /> </bean> <!-- 定義事務(wù)管理 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 定義 Autowired 自動(dòng)注入 bean --> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <!-- 掃描有注解的文件 base-package 包路徑 --> <context:component-scan base-package="tdxy"/> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 事務(wù)執(zhí)行方式 REQUIRED:指定當(dāng)前方法必需在事務(wù)環(huán)境中運(yùn)行, 如果當(dāng)前有事務(wù)環(huán)境就加入當(dāng)前正在執(zhí)行的事務(wù)環(huán)境, 如果當(dāng)前沒(méi)有事務(wù),就新建一個(gè)事務(wù)。 這是默認(rèn)值。 --> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="import*" propagation="REQUIRED" /> <!-- 指定當(dāng)前方法以非事務(wù)方式執(zhí)行操作,如果當(dāng)前存在事務(wù),就把當(dāng)前事務(wù)掛起,等我以非事務(wù)的狀態(tài)運(yùn)行完,再繼續(xù)原來(lái)的事務(wù)。 查詢定義即可 read-only="true" 表示只讀 --> <tx:method name="*" propagation="NOT_SUPPORTED" read-only="true" /> </tx:attributes> </tx:advice> <!-- 定義切面,在 * tdxy.*.service.*ServiceImpl.*(..) 中執(zhí)行有關(guān)的hibernate session的事務(wù)操作 --> <aop:config> <aop:pointcut id="serviceOperation" expression="execution(* tdxy.*.service.*Service.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" /> </aop:config> </beans>
applicationContext.xml 文件引用了一個(gè)properties文件 ,該文件也在src下,appConfig.properties 內(nèi)容可以自己定義
########################數(shù)據(jù)庫(kù)連接信息#############jdbc.username = rootjdbc.password = adminjdbc.url = jdbc:mysql://localhost:3306/tdxy?useUnicode=true&characterEncoding=UTF-8jdbc.driver = com.mysql.jdbc.Driver
自己寫(xiě)了一個(gè)test用的basedao
package tdxy.dao;import java.util.List;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;/** * * @Title: BaseDao.java * @Package tdxy.dao * @Description: TODO(baseDao 數(shù)據(jù)庫(kù)操作實(shí)現(xiàn)類) * @author dapeng * @date 2014年5月7日 下午5:09:22 * @version V1.0 */@Repositorypublic class BaseDao { /** * Autowired 自動(dòng)裝配 相當(dāng)于get() set() */ @Autowired protected SessionFactory sessionFactory; /** * gerCurrentSession 會(huì)自動(dòng)關(guān)閉session,使用的是當(dāng)前的session事務(wù) * * @return */ public Session getSession() { return sessionFactory.getCurrentSession(); } /** * openSession 需要手動(dòng)關(guān)閉session 意思是打開(kāi)一個(gè)新的session * * @return */ public Session getNewSession() { return sessionFactory.openSession(); } public void flush() { getSession().flush(); } public void clear() { getSession().clear(); } /** * 根據(jù) id 查詢信息 * * @param id * @return */ @SuppressWarnings("rawtypes") public Object load(Class c, String id) { Session session = getSession(); return session.get(c, id); } /** * 獲取所有信息 * * @param c * * @return */ @SuppressWarnings({ "rawtypes" }) public List getAllList(Class c) { String hql = "from " + c.getName(); Session session = getSession(); return session.createQuery(hql).list(); } /** * 獲取總數(shù)量 * * @param c * @return */ @SuppressWarnings("rawtypes") public Long getTotalCount(Class c) { Session session = getNewSession(); String hql = "select count(*) from " + c.getName(); Long count = (Long) session.createQuery(hql).uniqueResult(); session.close(); return count != null ? count.longValue() : 0; } /** * 保存 * * @param bean * */ public void save(Object bean) { try { Session session = getNewSession(); session.save(bean); session.flush(); session.clear(); session.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 更新 * * @param bean * */ public void update(Object bean) { Session session = getNewSession(); session.update(bean); session.flush(); session.clear(); session.close(); } /** * 刪除 * * @param bean * */ public void delete(Object bean) { Session session = getNewSession(); session.delete(bean); session.flush(); session.clear(); session.close(); } /** * 根據(jù)ID刪除 * * @param c 類 * * @param id ID * */ @SuppressWarnings({ "rawtypes" }) public void delete(Class c, String id) { Session session = getNewSession(); Object obj = session.get(c, id); session.delete(obj); flush(); clear(); } /** * 批量刪除 * * @param c 類 * * @param ids ID 集合 * */ @SuppressWarnings({ "rawtypes" }) public void delete(Class c, String[] ids) { for (String id : ids) { Object obj = getSession().get(c, id); if (obj != null) { getSession().delete(obj); } } }}
不知大家有沒(méi)有注意 applicationContext.xml 這樣一句代碼
<!-- 設(shè)置自動(dòng)創(chuàng)建|更新|驗(yàn)證數(shù)據(jù)庫(kù)表結(jié)構(gòu) --> hibernate.hbm2ddl.auto=update
這個(gè)意思是 只要在實(shí)體bean指定了entity,那么在數(shù)據(jù)庫(kù)會(huì)自動(dòng)創(chuàng)建對(duì)應(yīng)的表和表結(jié)構(gòu)
test用的一個(gè)實(shí)體bean
package tdxy.bean;import java.io.Serializable;import javax.persistence.Entity;import javax.persistence.Id;/** * * @ClassName: UserInfoBean * @Description: TODO(用戶信息類) * @author dapeng * @date 2014年5月7日 上午12:13:44 * @version V1.0 * */@Entitypublic class UserInfoBean implements Serializable { private static final long serialVersionUID = 7280747949998651159L; @Id private String id; /** * 昵稱 */ private String nickName; private String pwd; /** * 等級(jí) * */ private String level; /** * 經(jīng)驗(yàn)值 */ private String emValue; /** * 性別(0 男 1女) */ private String sex; private String birthday; private String qq; private String email; /** * 頭像 */ private String img; /** * 所在地 */ private String address; /** * 簽名 */ private String qmd; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getEmValue() { return emValue; } public void setEmValue(String emValue) { this.emValue = emValue; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getQmd() { return qmd; } public void setQmd(String qmd) { this.qmd = qmd; }}
當(dāng)應(yīng)用成功啟動(dòng)之后,數(shù)據(jù)庫(kù)會(huì)出現(xiàn)表和結(jié)構(gòu),即剛才定義的bean是一樣的,大家可以自己查看一下即可。
以下是test的Service
package tdxy.user.service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import tdxy.bean.UserInfoBean;import tdxy.dao.BaseDao;import tdxy.util.TdxyUtil;@Servicepublic class UserInfoService { @Autowired private BaseDao baseDao; public UserInfoBean queryUserInfoById(String id) { return (UserInfoBean) baseDao.load(UserInfoBean.class, id); } public void addUserInfo(UserInfoBean userInfo) { try { userInfo.setId(TdxyUtil.getId()); userInfo.setAddress("32132"); baseDao.save(userInfo); } catch (Exception e) { e.printStackTrace(); } }}
配置過(guò)程到此結(jié)束,希望大家一起討論共同進(jìn)步。
聯(lián)系客服