说明: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;
}
}
然后修改id字段修改为
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);
}
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();
}
}
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);
}
}
a,配置hibernate
新建hibernate的配置文件:new-others-hibernate-hibernate configuration file
org.hibernate.dialect.MySQL5InnoDBDialect
true
true
update
user=root
password=xsx127
driverclass=com.mysql.jdbc.Driver
jdbcurl=jdbc:mysql:///ssh_test
initPoolSize=5
maxPoolSize=20
新建ApplicationContext.xml
获取登陆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
信息: 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
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
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
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