spring 4. x + hibenate 4. x 설정 상세 설명
42855 단어 Hibernate4
이 박문 의 내용 은 주로 제 가 최근 에 정리 한 spring 4. x 와 hibenate 4. x 관련 설정 과 사용 방식 입 니 다. 물론 spring 3. x 와 hibenate 4. x 도 참고 할 수 있 습 니 다.
우선 프로필 웹. xml 에 다음 코드 를 추가 하면 됩 니 다.
<!-- spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/applicationContext.xml</param-value>
</context-param>
<!-- spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
그리고 세우다 applicationContext. xml 파일, src 에서.파일 내용 은 아래 와 같 습 니 다. 주석 은 제 가 가능 한 한 상세 하 게 쓰 겠 습 니 다.
<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" />
<!-- bean destroy-method="close" , , -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<!-- JDBC -->
<property name="driverClass" value="${jdbc.driver}" />
<!-- JDBC URL -->
<property name="jdbcUrl" value="${jdbc.url}" />
<!-- -->
<property name="user" value="${jdbc.username}" />
<!-- -->
<property name="password" value="${jdbc.password}" />
<!-- -->
<property name="initialPoolSize" value="5" />
</bean>
<!-- sessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- -->
<property name="dataSource" ref="dataSource" />
<!-- hibernate -->
<property name="hibernateProperties">
<value>
<!-- -->
hibernate.dialect=org.hibernate.dialect.MySQLDialect
<!-- | | -->
hibernate.hbm2ddl.auto=update
<!-- sql -->
hibernate.show_sql=true
<!-- sql, -->
hibernate.format_sql=true
<!-- -->
hibernate.cache.use_second_level_cache=false
<!-- -->
hibernate.cache.use_query_cache=false
<!-- -->
hibernate.jdbc.fetch_size=50
<!-- 、 、 -->
hibernate.jdbc.batch_size=50
<!-- -->
hibernate.connection.autocommit=true
<!-- hibernate JDBC -->
hibernate.connection.release_mode=auto
<!-- session hibernate4.x -->
hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
<!-- javax.persistence.validation.mode auto , classpath bean-validation**
none -->
javax.persistence.validation.mode=none
</value>
</property>
<!-- tdxy.bean -->
<property name="packagesToScan" value="tdxy.bean" />
</bean>
<!-- -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Autowired 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>
<!--
REQUIRED: ,
,
, 。
。
-->
<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" />
<!--
, , , , 。
read-only="true"
-->
<tx:method name="*" propagation="NOT_SUPPORTED" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- , * tdxy.*.service.*ServiceImpl.*(..) hibernate session -->
<aop:config>
<aop:pointcut id="serviceOperation" expression="execution(* tdxy.*.service.*Service.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
</aop:config>
</beans>
applicationContext. xml 파일 은 properties 파일 을 참조 하 였 으 며, 이 파일 도 src 에서 app Config. properties 내용 을 스스로 정의 할 수 있 습 니 다.
######################## #############
jdbc.username = root
jdbc.password = admin
jdbc.url = jdbc:mysql://localhost:3306/tdxy?useUnicode=true&characterEncoding=UTF-8
jdbc.driver = com.mysql.jdbc.Driver
테스트 용 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 )
* @author dapeng
* @date 2014 5 7 5:09:22
* @version V1.0
*/
@Repository
public class BaseDao {
/**
* Autowired get() set()
*/
@Autowired
protected SessionFactory sessionFactory;
/**
* gerCurrentSession session, session
*
* @return
*/
public Session getSession() {
return sessionFactory.getCurrentSession();
}
/**
* openSession session session
*
* @return
*/
public Session getNewSession() {
return sessionFactory.openSession();
}
public void flush() {
getSession().flush();
}
public void clear() {
getSession().clear();
}
/**
* 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();
}
/**
*
*
* @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();
}
/**
* 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);
}
}
}
}
applicationContext. xml 라 는 코드 에 주의 하 셨 는 지 모 르 겠 습 니 다.
<!-- | | -->
hibernate.hbm2ddl.auto=update
이 뜻 은 실체 bean 에 entity 를 지정 하면 데이터베이스 에 해당 하 는 표 와 표 구 조 를 자동 으로 만 든 다 는 것 이다.
test 용 실체 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
*
*/
@Entity
public class UserInfoBean implements Serializable {
private static final long serialVersionUID = 7280747949998651159L;
@Id
private String id;
/**
*
*/
private String nickName;
private String pwd;
/**
*
*
*/
private String level;
/**
*
*/
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;
}
}
응용 프로그램 이 성공 적 으로 시 작 된 후에 데이터 베 이 스 는 표 와 구조 가 나타 납 니 다. 즉, 방금 정 의 된 bean 은 똑 같 습 니 다. 여러분 이 직접 확인 하 시 면 됩 니 다.
다음은 test 의 서비스 입 니 다.
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;
@Service
public 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();
}
}
}
배치 과정 은 여기 서 끝 났 으 니 모두 함께 토론 하고 함께 발전 하 기 를 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Spring3 통합 Hibernate4Spring3 통합 Hibernate4 참고 사항: 1.jar 패키지 참고 프로젝트에 가져오려면 jaxen-1.1-beta-6.jar와commons-logging-api.jar, commons-logging-1.1....
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.