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

    运行结果:

  • 相关阅读:
    SDUT2389Ballot evaluation
    POJ2941 SDUT2371Homogeneous squares
    SDUT1570 C旅行
    应用jQuery实现表格数据的动态添加与统计
    抢火车票利器:分享一个抓取火车票转让信息的小程序
    10款精选的用于构建良好易用性网站的jQuery插件
    数据库拷贝的问题
    sqlserver 2008手工修改表结构,表不能保存的问题与解决方法
    mysql 1067错误的处理
    40个有用的jQuery技术和教程
  • 原文地址:https://www.cnblogs.com/ligui989/p/3441613.html
Copyright © 2020-2023  润新知