JPA-Table主键生成策略和简单注解

@Table(name="customers") 
@Entity
public class Customer {

    private Integer id;
    private String lastname;
    private String email;
    private Integer age;
    private Date birthday;
    private Date creattime;
    
    @TableGenerator(name="id_generator",//和generator对应
            pkColumnName="pk_name",
            pkColumnValue="customers_id",
            valueColumnName="pk_value",
            allocationSize=100)
    @GeneratedValue(strategy=GenerationType.TABLE,generator="id_generator")
    @Id             //strategy:战略,策略                         generator:生成,生产  
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    @Column(name="last_name",nullable=false,length=50)
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    
    @Temporal(TemporalType.DATE)
    //调整Date类型的精度
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    
    public Date getCreattime() {
        return creattime;
    }
    public void setCreattime(Date creattime) {
        this.creattime = creattime;
    }
    @Transient  //表示该属性并非一个到数据库表的字段的映射,ORM框架将忽略该属性
    public String getInfo(){
        return "lastName : " + lastname + "email : "+ email;
    }
}


Main.java类

public class Main {

    public static void main(String[] args) {
        //1.创建EntitymanagerFactory
   //<persistence-unit name="jpa-1" transaction-type="RESOURCE_LOCAL">与下面unitname一致
  String persistenceUnitName="jpa-1";
        EntityManagerFactory factory=Persistence.createEntityManagerFactory(persistenceUnitName);
        
        //2.创建Entitymanager
        EntityManager manager=factory.createEntityManager();
        
        //3.开启事务
        EntityTransaction transaction = manager.getTransaction();
        transaction.begin();
        
        //4.进行持久化操作
        Customer customer = new Customer();
        customer.setAge(12);
        customer.setEmail("jcc@163.com");
        customer.setLastname("jcc");
        customer.setBirthday(new Date());
        customer.setCreattime(new Date());
        manager.persist(customer);
        
        //5.提交事务
        transaction.commit();
        
        //6.关闭Entitymanager
        manager.close();
        
        //7.关闭EntitymanagerFactory
        factory.close();
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值