码迷,mamicode.com
首页 > 其他好文 > 详细

JPA測试实例

时间:2017-06-19 19:41:21      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:admin   action   comm   span   manage   factor   vax   class   .com   

依赖架包

技术分享

实体

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
 * 持久化实体类使用注解配置
 * @author Administrator
 *
 */
@Table
@Entity
public class Customer {
    private int id;
    private String username;
    private int age;
    private String email;
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
//其它数据可能和实体实体属性相应的能够不加注解
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Transient
public String getInfo(){
return "name:"+username+",age"+age+",email"+email;
}


測试类

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;


public class TestOrm {
    public static void main(String[] args){
    //创建EntityManagerFactory
    String str="jpa";
    EntityManagerFactory factory=Persistence.createEntityManagerFactory(str);
    //创建EntityManager
    EntityManager manager=factory.createEntityManager();
    //声明事务
    EntityTransaction transation=manager.getTransaction();
    transation.begin();
    //持久化操作
    Customer cus=new Customer();
    //cus.setId(1);
    cus.setUsername("xxxx");
    cus.setAge(23);
    cus.setEmail("12122121@qq.com");
   
    manager.persist(cus);//保存
    //提交事务
    transation.commit();
        //关闭EntityMnager
    manager.close();
    //关闭EnetityManagerFactory
    factory.close();
    }
}

JPA測试实例

标签:admin   action   comm   span   manage   factor   vax   class   .com   

原文地址:http://www.cnblogs.com/jzssuanfa/p/7049962.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!