码迷,mamicode.com
首页 > Web开发 > 详细

hibernate

时间:2016-07-31 12:57:09      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

1.hibernate.cfg.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<!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="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <mapping resource="com/finn/pojo/User.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

2.配置User.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    
<hibernate-mapping package="com.finn.pojo">
    <class name="User" table="user">
        <id name="id" column="id" type="int">
            <generator class="native"></generator>
        </id>
        
        <property name="uname" type="string" not-null="true">
            <column name="uname"/>
        </property>
        
        <property name="upwd" type="string" not-null="true">
            <column name="upwd" />
        </property>
    </class>
</hibernate-mapping>

3.实例化调用

    //1.创建Configuration,该对象用于读取hibernate.cfg.xml文件并初始化
        Configuration cfg = new Configuration().configure();
        //2.创建SessionFactory,只有一个
        SessionFactory sf = cfg.buildSessionFactory();
        //3.创建Session
        Session session = sf.openSession();
        //4.增加、删除、修改  强制要求用事务提交
        Transaction ts = session.beginTransaction(); //开启事务
        User user = new User();
        
        user.setUname("zhangxueyou");
        user.setUpwd("zxyhi");
        
        session.save(user);
        
        ts.commit();
        session.close();

 

hibernate

标签:

原文地址:http://www.cnblogs.com/finnlee1220/p/5722729.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!