Happiness is more than pleasure without pain

你只有非常努力,才能看起来毫不费力

导航

Hibernate简单配置

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();
    }

 

posted on 2015-03-10 20:45  believer  阅读(199)  评论(0编辑  收藏  举报