zoukankan      html  css  js  c++  java
  • 建立Annotation版本的HelloWorld

    annotation @符号加后面一个名字

    使用annotation需要的包3个:

    hibernate annnotation.jar

    ejb3 oersistence.jar

    hibernate common annotation.jar

    JPA是标准,hibernate是实现

    建实体类Teacher.java,使用注解表明实体,主键。

    package hjj.lch.hibernate.model;
    
    import javax.persistence.Entity;
    import javax.persistence.Id;
    
    @Entity
    public class Teacher {
        
        private int id; // 编号
        private String name; // 姓名
        private String title; // 职称
        
        @Id // 主键
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getTitle() {
            return title;
        }
        public void setTitle(String title) {
            this.title = title;
        }
    }

    建表teacher

    在hibernate.cfg.xml文件中加入

    <mapping class="hjj.lch.hibernate.model.Teacher"/>

    hibernate 的xml和annotation是不是不能同时使用?
    不能!!!!也就是
      <mapping resource="hjj/lch/hibernate/model/Student.hbm.xml"/>
            
           <mapping class="hjj.lch.hibernate.model.Teacher"/>
    不能共存,否则xml就用不了。。

    再写测试类TeacherTest.java

    package hjj.lch.hibernate.model;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.AnnotationConfiguration;
    import org.hibernate.cfg.Configuration;
    
    public class TeacherTest {
    
        public static void main(String[] args) {
            Teacher t = new Teacher(); // 创建student对象
            t.setId(1);
            t.setName("t1");
            t.setTitle("中级");
            
            // 解析hibernate.cfg.xml,拿到session
            // 使用Annotation时,不能new 普通的Configuration,要new一个专门的AnnotationConfiguration
            Configuration cfg = new AnnotationConfiguration(); // 用于解析hibernate.cfg.xml
            SessionFactory sf = cfg.configure().buildSessionFactory(); // 产生session工厂,可以想象成数据库的connection
            Session session = sf.openSession();
            
            session.beginTransaction();
            session.save(t);
            session.getTransaction().commit();
            session.close();
            sf.close();
        }
    }

    运行结果:

  • 相关阅读:
    php没有输出报错信息的解决
    web服务器集群(多台web服务器)后session如何同步和共享
    Linux环境PHP7安装
    Linux下将Mysql和Apache加入到系统服务
    2017年PHP程序员未来路在何方——韩天峰
    完整的TCP连接详解
    PHP常用优化
    socket_listen里面第二个参数backlog的用处
    JavaScript中的值类型和引用类型
    查询mysql字段名和字段注释
  • 原文地址:https://www.cnblogs.com/ligui989/p/3441613.html
Copyright © 2011-2022 走看看