目录
【IT之路】MyEclipse实现Hibernate集成(一)
【IT之路】MyEclipse实现Hibernate集成(二)
一、MyEclipse实现Hibernate集成步骤
1、搭建Spring+Struts2+Maven项目
2、添加Hibernate配置文件,名字可以自定义。
3、添加config配置文件
4、增加实体类
5、增加DAO
6、修改spring配置文件,增加config配置文件的导入
7、编写测试类,测试类中主动导入spring和hibernate配置文件
二、搭建Spring+Struts2+Maven项目
略
三、添加Hibernate配置文件,名字可以自定义。
<?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" xmlns:aop="http://www.springframework.org/schema/aop" 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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">
<!-- JNDI方式配置数据源 -->
<!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> -->
<!-- 配置数据源 -->
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_username}" />
<property name="password" value="${jdbc_password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="0" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20" />
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="20" />
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000" />
<!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> -->
<property name="validationQuery" value="${validationQuery}" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000" />
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="true" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="1800" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true" />
<!-- 监控数据库 -->
<!-- <property name="filters" value="stat" /> -->
<property name="filters" value="mergeStat" />
</bean>
<!-- 配置hibernate session工厂 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
</props>
</property>
<!-- 自动扫描注解方式配置的hibernate类文件 -->
<property name="packagesToScan">
<list>
<value>com.maventest.model</value>
</list>
</property>
<!-- 自动扫描hbm方式配置的hibernate文件和.hbm文件 -->
<!--
<property name="mappingDirectoryLocations">
<list>
<value>classpath:com/maventest/model/hbm</value>
</list>
</property>
-->
</bean>
<!-- 配置事务管理器 -->
<bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 注解方式配置事物 -->
<!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->
<!-- 拦截器方式配置事物 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" />
<tx:method name="save*" />
<tx:method name="update*" />
<tx:method name="modify*" />
<tx:method name="edit*" />
<tx:method name="delete*" />
<tx:method name="remove*" />
<tx:method name="repair" />
<tx:method name="deleteAndRepair" />
<tx:method name="get*" propagation="SUPPORTS" />
<tx:method name="find*" propagation="SUPPORTS" />
<tx:method name="load*" propagation="SUPPORTS" />
<tx:method name="search*" propagation="SUPPORTS" />
<tx:method name="datagrid*" propagation="SUPPORTS" />
<tx:method name="*" propagation="SUPPORTS" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* com.maventest.service..*Impl.*(..))" />
<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
</aop:config>
</beans>
四、添加config配置文件
#hibernate.dialect=org.hibernate.dialect.OracleDialect
#driverClassName=oracle.jdbc.driver.OracleDriver
#validationQuery=SELECT 1 FROM DUAL
#jdbc_url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
#jdbc_username=test
#jdbc_password=test
hibernate.dialect=org.hibernate.dialect.MySQLDialect
driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc_username=root
jdbc_password=test
#hibernate.dialect=org.hibernate.dialect.SQLServerDialect
#driverClassName=net.sourceforge.jtds.jdbc.Driver
#validationQuery=SELECT 1
#jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/sy
#jdbc_username=test
#jdbc_password=123456
#jndiName=java:comp/env/dataSourceName
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=true
sessionInfoName=sessionInfo
uploadFieldName=filedata
uploadFileMaxSize=20971520
uploadFileExts=txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid
uploadDirectory=attached
五、增加实体类
package com.maventest.model;
import java.lang.reflect.Field;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* Account entity. @author MyEclipse Persistence Tools
*/
@Entity
@Table(name = "ACCOUNT", schema = "TEST", uniqueConstraints = @UniqueConstraint(columnNames = "NAME"))
public class Account implements java.io.Serializable {
// Fields
/**
*
*/
private static final long serialVersionUID = 1L;
private String id;
private String name;
private String pwd;
private Date createdatetime;
private Date modifydatetime;
// Constructors
/** default constructor */
public Account() {
}
/** minimal constructor */
public Account(String id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
/** full constructor */
public Account(String id, String name, String pwd, Date createdatetime, Date modifydatetime) {
this.id = id;
this.name = name;
this.pwd = pwd;
this.createdatetime = createdatetime;
this.modifydatetime = modifydatetime;
}
// Property accessors
@Id
@Column(name = "ID", unique = true, nullable = false, length = 36)
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
@Column(name = "NAME", unique = true, nullable = false, length = 100)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "PWD", nullable = false, length = 32)
public String getPwd() {
return this.pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "CREATEDATETIME", length = 7)
public Date getCreatedatetime() {
return this.createdatetime;
}
public void setCreatedatetime(Date createdatetime) {
this.createdatetime = createdatetime;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "MODIFYDATETIME", length = 7)
public Date getModifydatetime() {
return this.modifydatetime;
}
public void setModifydatetime(Date modifydatetime) {
this.modifydatetime = modifydatetime;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
}
@Override
public String toString() {
//重写toString方法
//return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
//重写toString方法,过滤掉Paasword,不打印Password属性
return (new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) {
@Override
protected boolean accept(Field f) {
return super.accept(f) && !f.getName().equalsIgnoreCase("password"); //过滤掉特殊字段
}
}).toString();
}
}
六、增加DAO
/**
*
*/
package com.maventest.dao.impl;
import java.io.Serializable;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.maventest.dao.AccountDaoI;
import com.maventest.model.Account;
/**
* @author MyPC
*
*/
@Repository("accountDao")
public class AccountDaoImpl implements AccountDaoI {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public Serializable save(Account account) {
return this.sessionFactory.getCurrentSession().save(account);
}
}
七、修改spring配置文件,增加config配置文件的导入
<!-- 引入属性文件 -->
<context:property-placeholder location="classpath:config.properties" />
八、编写测试类,测试类中主动导入spring和hibernate配置文件
/**
*
*/
package com.maventest.account;
import org.apache.log4j.Logger;
import java.util.Date;
import java.util.UUID;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.maventest.model.Account;
import com.maventest.service.AccountServiceI;
/**
* @author MyPC
*
*/
public class TestAccount {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(TestAccount.class);
@Test
public void test(){
ApplicationContext ac=new ClassPathXmlApplicationContext(new String[]{"classpath:spring.xml","classpath:spring-hibernate.xml"});
AccountServiceI userService=(AccountServiceI) ac.getBean("accountService");
Account account=new Account();
account.setId(UUID.randomUUID().toString());
account.setName("七星云-恒312");
account.setPwd("Smil112243");
logger.info("=============================fdsafds==============");
logger.info(account);
account.setCreatedatetime(new Date());
userService.addAccount(account);
}
}

本文介绍了如何在MyEclipse环境中实现Hibernate的集成,包括搭建Spring+Struts2+Maven项目,配置Hibernate,创建实体类和DAO,修改Spring配置文件以及编写测试类进行验证。
&spm=1001.2101.3001.5002&articleId=89710305&d=1&t=3&u=2e02d935f5f9411eb8e861a16bbed324)
1322

被折叠的 条评论
为什么被折叠?



