说明:hibernate环境搭建承接与spring环境,请看spring环境搭建笔记
一,开发环境
工具:eclipse
Spring:4.3.1
Commons-logging:1.1.1
Hibernate: 5.1.0
二,添加hibernate环境
hibernate的jar包位置:D:\Program Files\hibernate-release-5.1.0.Final\lib\required
目前只需用这个文件夹下的jar包即可
三,代码
1,建立bean
beans包:org\com\xsx\beans 包下包含userbean.java
package org.com.xsx.beans;
public class UserBean {
private int id;
private String account;
private String password;
private String name;
private String sex;
private Integer age;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
依据此bean,建立hibernate的map xml文件,右键-new-others-hibernate-hibernate xml mapping file,hibernate插件会自动根据bean配置好
然后修改id字段修改为 <generator class="native" />
2,建立dao
a,先建立dao的接口
包org\com\xsx\daos\InterFace, 包含文件UserDaoInterFace.java, 这里只实现简单的登陆例子,所以只实现根据账户和密码查询用户的方法
package org.com.xsx.daos.InterFace;
import org.com.xsx.beans.UserBean;
public interface UserDaoInterFace {
public UserBean ReadUserByLoginInfo(String account, String password);
}
b,建立实际的dao daos:org\com\xsx\daos。 包含UserDao.java
package org.com.xsx.daos;
import org.com.xsx.beans.UserBean;
import org.com.xsx.daos.InterFace.UserDaoInterFace;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class UserDao implements UserDaoInterFace{
@Autowired
private SessionFactory sessionFactory;
private Session getSession() {
return sessionFactory.getCurrentSession();
}
@Override
public UserBean ReadUserByLoginInfo(String account, String password) {
// TODO Auto-generated method stub
String hql = "select p from UserBean as p where p.account = :myaccount AND p.password = :mypassword";
Query query = getSession().createQuery(hql);
query.setParameter("myaccount", account);
query.setParameter("mypassword", password);
return (UserBean)query.uniqueResult();
}
}
3,建立service层
1, services的接口:org\com\xsx\services\InterFace, 文件LoginServiceInterFace.java
package org.com.xsx.services.InterFace;
import org.com.xsx.beans.UserBean;
public interface LoginServiceInterFace {
public UserBean Login(String account, String password);
}
2, services:org\com\xsx\services,文件LoginService.java
package org.com.xsx.services;
import org.com.xsx.beans.UserBean;
import org.com.xsx.daos.UserDao;
import org.com.xsx.services.InterFace.LoginServiceInterFace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class LoginService implements LoginServiceInterFace{
@Autowired
private UserDao userDao;
@Override
public UserBean Login(String account, String password) {
// TODO Auto-generated method stub
return userDao.ReadUserByLoginInfo(account, password);
}
}
4,所有代码已完成,接下来配置spring和hibernate
a,配置hibernate
新建hibernate的配置文件:new-others-hibernate-hibernate configuration file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
这里只简单的配置了一些常用属性,其他的根据数据库有差异的属性在数据库的properties文件中配置,方便修改,新建SQL.properties文件
user=root
password=xsx127
driverclass=com.mysql.jdbc.Driver
jdbcurl=jdbc:mysql:///ssh_test
initPoolSize=5
maxPoolSize=20
b,配置spring与hibernate的关联
新建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:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!--
用于配置hibernate
-->
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="org.com.xsx"></context:component-scan>
<!-- 设置数据库配置文件位置 -->
<context:property-placeholder location="SQL.properties"/>
<bean id="MyDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="driverClass" value="${driverclass}"></property>
<property name="jdbcUrl" value="${jdbcurl}"></property>
<property name="initialPoolSize" value="${initPoolSize}"></property>
<property name="maxPoolSize" value="${maxPoolSize}"></property>
</bean>
<bean id="MySeesionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="MyDataSource"></property>
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
<property name="mappingLocations" value="classpath:org/com/xsx/beans/*.hbm.xml"></property>
</bean>
<bean id="MyTransActionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="MySeesionFactory"></property>
</bean>
<tx:advice id="MyTxAdvice" transaction-manager="MyTransActionManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="MyTxPointcut" expression="execution(* org.com.xsx.services.*.*(..))" />
<aop:advisor advice-ref="MyTxAdvice" pointcut-ref="MyTxPointcut"/>
</aop:config>
</beans>
四,测试
获取登陆service,从数据库从获取用户信息打印,如果不存在则会打印null,预先在数据库中写入一些测试数据
package org.com.xsx.unit;
import org.com.xsx.beans.UserBean;
import org.com.xsx.services.InterFace.LoginServiceInterFace;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestUnits {
private ApplicationContext ctx = null;
private LoginServiceInterFace loginservice = null;
{
ctx = new ClassPathXmlApplicationContext("ApplicationContext.xml");
loginservice = ctx.getBean(LoginServiceInterFace.class);
}
@Test
public void test1(){
UserBean user = loginservice.Login("xsx0", "xsx1270");
System.out.println(user.getName());
}
}
测试结果如下:
八月 13, 2016 7:59:03 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@7d4793a8: startup date [Sat Aug 13 19:59:03 CST 2016]; root of context hierarchy
八月 13, 2016 7:59:03 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [ApplicationContext.xml]
八月 13, 2016 7:59:03 下午 org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
信息: Loading properties file from class path resource [SQL.properties]
八月 13, 2016 7:59:03 下午 com.mchange.v2.log.MLog <clinit>
信息: MLog clients using java 1.4+ standard logging.
八月 13, 2016 7:59:03 下午 com.mchange.v2.c3p0.C3P0Registry banner
信息: Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10]
八月 13, 2016 7:59:04 下午 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.0.Final}
八月 13, 2016 7:59:04 下午 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
八月 13, 2016 7:59:04 下午 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
八月 13, 2016 7:59:04 下午 org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
八月 13, 2016 7:59:04 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
八月 13, 2016 7:59:05 下午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager
信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge0wf9i10k7l311c1fao0|6302bbb1, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge0wf9i10k7l311c1fao0|6302bbb1, idleConnectionTestPeriod -> 0, initialPoolSize -> 5, jdbcUrl -> jdbc:mysql:///ssh_test, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]
八月 13, 2016 7:59:05 下午 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
八月 13, 2016 7:59:05 下午 org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
八月 13, 2016 7:59:05 下午 org.springframework.orm.hibernate5.HibernateTransactionManager afterPropertiesSet
信息: Using DataSource [com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge0wf9i10k7l311c1fao0|6302bbb1, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge0wf9i10k7l311c1fao0|6302bbb1, idleConnectionTestPeriod -> 0, initialPoolSize -> 5, jdbcUrl -> jdbc:mysql:///ssh_test, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]] of Hibernate SessionFactory for HibernateTransactionManager
八月 13, 2016 7:59:06 下午 org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate:
select
userbean0_.ID as ID1_0_,
userbean0_.ACCOUNT as ACCOUNT2_0_,
userbean0_.PASSWORD as PASSWORD3_0_,
userbean0_.NAME as NAME4_0_,
userbean0_.SEX as SEX5_0_,
userbean0_.AGE as AGE6_0_,
userbean0_.EMAIL as EMAIL7_0_
from
USERBEAN userbean0_
where
userbean0_.ACCOUNT=?
and userbean0_.PASSWORD=?
xsx0