隔了这么久,终于有时间来学学Hibernate了,话说配置还真繁杂。
在开发过程中,经常看到分层现象,主要目的是为了解耦。
B/S最少分三层:
view 表示层
action/sevlet/xx 数据
jsp 模板
service 业务层
dao 数据访问层
下面是真正的Hibernate入门。
首先是导入一些必须的jar包;数据库采用MySQL,连接数据库当然要数据库驱动包。
工程目录:
调试建的工程是Java Project
实体类User.java
package test.hibernate.domain; public class User { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { // TODO Auto-generated method stub return "[User:id="+id+",name:"+name+"]"; } }
配置文件hibernate.cfg.xml,其中文件名是hibernate.cfg
<!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 name="foo"> <!-- 配置数据库信息 --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/hibernate_2015</property> <!-- 可简写为<property name="connection.url">jdbc:mysql:///hibernate_2015</property> --> <property name="connection.username">root</property> <property name="connection.password">686175</property> <!-- 显示生成的sql语句,不写的话默认是false --> <property name="show_sql">true</property> <mapping resource="test/hibernate/domain/User.hbm.xml"/> </session-factory> </hibernate-configuration>
对象与表的映射文件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="test.hibernate.domain"> <class name="User" table="t_user"> <id name="id" type="integer" column="id"> <generator class="native"/> </id> <property name="name" type="string" column="name"/> </class> </hibernate-mapping>
id的class属性值取为native表示采用数据库中的配置属性
主要测试类App.java
package test.hibernate.domain; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.classic.Session; import org.junit.Test; public class App { private static SessionFactory sessionFactory; static{ Configuration cfg=new Configuration(); cfg.configure("hibernate.cfg.xml"); sessionFactory=cfg.buildSessionFactory(); } @Test public void testSave() throws Exception { User user=new User(); user.setName("张三"); Session session=sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); session.save(user); transaction.commit(); session.close();//关闭session,释放资源 } @Test public void testGet() throws Exception { Session session=sessionFactory.openSession(); Transaction transaction=session.beginTransaction(); User user=(User) session.get(User.class, 1); System.out.println(user); transaction.commit(); session.close(); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。转载请注明出处http://blog.csdn.net/lindonglian
时间: 2024-11-06 13:35:07