• hibernate(二)annotation第一个示例


    一、在数据库中创建teacher表(数据库hibernate)

    create table teache(
    id int auto_increment primary key,
    name varchar(20),
    title varchar(20)
    );

    二、创建model

    在cn.orlion.hibernate.model下创建实体类Teacher(注意添加注解,一开始只添加了@Id,然后抛出异常,后来又加上了@GeneratedValue(strategy = GenerationType.AUTO))

    package cn.orlion.hibernate.model;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    
    @Entity
    public class Teacher{
    
        private int id;
        
        private String name;
        
        private String title;
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        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;
        }
    }

    三、在配置文件中配置类:

    在hibernate.cfg.xml中添加下面一行

    <mapping class="cn.orlion.hibernate.model.Teacher" />

    OK,配置完成写一个测试:

    package cn.orlion.test;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.AnnotationConfiguration;
    import org.hibernate.cfg.Configuration;
    
    import cn.orlion.hibernate.model.Teacher;
    
    public class TeacherTest {
        
        public static void main(String[] args){
            
            Teacher t = new Teacher();
            
            t.setName("test1");
            t.setTitle("title1");
            
            Configuration cfg = new AnnotationConfiguration();
            
            SessionFactory sf = cfg.configure().buildSessionFactory();
            
            Session session = sf.openSession();
            
            session.beginTransaction();
            session.save(t);
            session.getTransaction().commit();
            
            session.close();
            
            sf.close();
        }
    }

    运行可以看到数据库中添加了一条记录。

  • 相关阅读:
    1051 Wooden Sticks(贪心-3)
    97 等价交换(贪心-2)
    python文件操作
    python学习-day 2
    python学习-day 1
    Python 测试题目-1
    Python list和dict方法
    Python 字符串
    while循环语句
    Python if判断语句
  • 原文地址:https://www.cnblogs.com/orlion/p/5040438.html
Copyright © 2020-2023  润新知