eclipse之SSH配置hibernate【三】
配置hibernate,没有和spring整合,可以看成独立的部分。
在src下创建hibernate配置文件,hibernate.cfg.xml。主要是sql连接相关配置。
<?xml version='1.0' encoding='utf-8'?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver </property>
<property name="connection.url">jdbc:mysql://localhost:3306/cmsadmin</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect </property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<mapping resource="com/awu/models/user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Tip:<mapping resource="com/awu/models/user.hbm.xml"/> 是entity的映射文件。一般创建在src的目录下即可。内容如:
<?xml version="1.0" encoding="UTF-8"?> <hibernate-mapping package="com.awu.models"> <class name="User" table="user"> <id name="userid" type="string"> </id> <property name="username" type="string"></property> <property name="pwd" type="string"></property> <property name="creator" type="string"></property> <property name="createtime" type="date"></property> <property name="updater" type="string"></property> <property name="updatetime" type="date"></property> <property name="isenabled" type="int"></property> </class> </hibernate-mapping>
使用hibernate示例代码:
Configuration configuration = new Configuration().configure();
SessionFactory factory = configuration.buildSessionFactory();
Session session = null;
try{
session = factory.openSession();
session.beginTransaction();
// ArrayList<User> result = (ArrayList<User>) session.createQuery("from User").list();
session.createQuery("from User").uniqueResult();
System.out.println(session.get(User.class,"402895da5a6def38015a6def39d80000").getUsername());
session.getTransaction().commit();
}catch (Exception e) {
System.out.println(e.getMessage());
session.getTransaction().rollback();
}finally {
if(session != null){
if(session.isOpen())
session.close();
}
}
hibernate相关的jar。
- antlr-2.7.7.jar
- classmate-1.3.0.jar
- dom4j-1.6.1.jar
- hibernate-commons-annotations-5.0.1.Final.jar
- hibernate-core-5.2.8.Final.jar
- hibernate-jpa-2.1-api-1.0.0.Final.jar
- jandex-2.0.3.Final.jar
- javassist-3.20.0-GA.jar
- jboss-logging-3.3.0.Final.jar
- jboss-transaction-api_1.2_spec-1.0.1.Final.jar
mysql连接库:
- mysql-connector-java-5.1.40-bin.jar
浙公网安备 33010602011771号