首页 > 代码库 > JPA測试实例

JPA測试实例

依赖架包

技术分享

实体

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測试实例