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

Hibernate简单配置

时间:2015-03-10 21:04:23      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

1.配置构建路径,加载用户库,hibernate4.3.8 MySQL-Driver

2.写User.java      纯POJO+持久化注解=PO

@Entity
@Table(name="user")
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;
...

 

3.配置hibernate.cfg.cml

<?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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
        <property name="hbm2ddl.auto">update</property>
        <property name="show_sql">true</property>        
        <mapping class="org.crazyit.app.domain.User"/>
    </session-factory>
</hibernate-configuration>

4.调用即可创建数据库表并更新记录

public static void main(String[] args)
        throws Exception
    {
        // 实例化Configuration,
        Configuration conf = new Configuration()
        // 不带参数的configure()方法默认加载hibernate.cfg.xml文件,
        // 如果传入abc.xml作为参数,则不再加载hibernate.cfg.xml,改为加载abc.xml
            .configure();
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(conf.getProperties()).build();
        // 以Configuration实例创建SessionFactory实例
        SessionFactory sf = conf.buildSessionFactory(serviceRegistry);
        // 创建Session
        Session sess = sf.openSession();
        // 开始事务
        Transaction tx = sess.beginTransaction();
        // 创建消息对象   
        User u=new User();
        u.setUsername("dddd");
        u.setPassword("iiiiii");
        
  
        // 保存消息
        sess.save(u);
        sess.save(n);
        // 提交事务
        tx.commit();
        // 关闭Session
        sess.close();
        sf.close();
    }

 

Hibernate简单配置

标签:

原文地址:http://www.cnblogs.com/gaoxiangde/p/4328381.html

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