zoukankan      html  css  js  c++  java
  • 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();
        }

     

  • 相关阅读:
    Explain用法
    轻量快速的 Python ASGI 框架 uvicorn
    conda常用命令
    ubuntu 安装并配置zsh
    ubuntu安装zsh终端
    /etc/profile、/etc/bashrc、.bash_profile、.bashrc
    python用List的内建函数list.sort进行排序
    python对象排序
    修改python接口返回给前端的格式封装
    linux设置uwsgi开机自启
  • 原文地址:https://www.cnblogs.com/gaoxiangde/p/4328381.html
Copyright © 2011-2022 走看看