首页 > 代码库 > Hibernate环境搭建
Hibernate环境搭建
1、导入jar包
hibernate.jar
antlr-2.7.6.jar
commons-collections-3.1.jar
jta-1.1.jar
dom4j-1.6.1.jar
javassist-3.4.GA.jar
slf4j-api-1.5.2.jar
slf4j-log4j12-1.5.2.jar
如果使用C3P0数据源实现数据库连接:c3p0-0.9.0.4.jar
如果使用mysql数据库,Mysql JDBC驱动: mysql-connector.jar
2、写配置文件
建立一个User实体类,测试用。
package cn.itcast.hibernate.domain; import java.util.Date; public class User { private long id; private String name; private Date birthday; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }
写User.hbm.xml配置文件:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.itcast.hibernate.domain"> <class name="User" table="itcast_user"> <id name="id"> <generator class="native" /> </id> <property name="name" /> <property name="birthday" /> </class> </hibernate-mapping>
写Hibernate主配置文件hibernate.cfg.xml
<?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> <!-- 1,数据库连接信息 --> <property name="dialect"> org.hibernate.dialect.MySQL5InnoDBDialect </property> <property name="connection.url">jdbc:mysql:///rowsy</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- 2,其他配置 --> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <!-- 3,导入映射文件 --> <mapping resource="cn/itcast/hibernate/domain/User.hbm.xml" /> </session-factory> </hibernate-configuration>
3、测试
写一个测试类:
package cn.itcast.hibernate; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import cn.itcast.hibernate.domain.User; public class Base { public static void main(String[] args) { SessionFactory sessionFactory = new Configuration().configure() .buildSessionFactory(); Session session = sessionFactory.openSession(); User user = new User(); user.setBirthday(new Date()); user.setName("ronnie"); Transaction transaction=session.beginTransaction(); session.save(user); transaction.commit(); session.close(); } }
4、运行成功!
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。