保存一个对象到数据库中
目录结构
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!--数据库连接信息--> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/Lesson7_Hibernate3_Demo1</property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <!--方言--> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!--参数信息--> <!--显示sql--> <property name="show_sql">true</property> <!--如果没有表 自动创建--> <property name="hbm2ddl.auto">create</property> <!-- <property name="c3p0.max_size">100</property> <property name="c3p0.min_size">10</property> <property name="cache.use_second_level_cache">true</property> <property name="cache.use_query_cache">true</property> <property name="cache.provider_class">org.hibernate.cache.OSCacheProvider</property> <property name="generate_statistics">true</property>--> <!-- <class-cache class="cn.itcast.hibernate.domain.User" usage="read-only"/> --> <!--映射文件--> <mapping resource="org/zln/hibernate/domain/hbm/User.hbm.xml"/> </session-factory> </hibernate-configuration>
HibernateUtils.java
package org.zln.hibernate.utils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** * Created by coolkid on 2015/6/14 0014. */ public class HibernateUtils { private static Configuration configuration = new Configuration(); private static SessionFactory sessionFactory; private static final String PATH = "hibernate.cfg.xml"; static { configuration.configure(PATH); } public static Session getSession(){ sessionFactory = configuration.buildSessionFactory(); return sessionFactory.openSession(); } }
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="org.zln.hibernate.domain"> <class name="User"> <id name="id"> <generator class="native"/> </id> <property name="name"/> <property name="birthday"/> </class> </hibernate-mapping>
UserDao.java
package org.zln.hibernate.dao; import org.hibernate.Session; import org.hibernate.Transaction; import org.zln.hibernate.domain.User; import org.zln.hibernate.utils.HibernateUtils; /** * Created by coolkid on 2015/6/14 0014. */ public class UserDao { public void saveUser(User user){ Session session = HibernateUtils.getSession(); Transaction transaction = session.beginTransaction(); try { session.save(user); session.flush(); transaction.commit(); }finally { session.close(); } } }
时间: 2024-10-31 15:06:09