1. 程式人生 > >JPA測試實例

JPA測試實例

使用註解 () mail .get 事務 customer tid bsp set

依賴架包

技術分享

實體

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("[email protected]");

manager.persist(cus);//保存
//提交事務
transation.commit();
//關閉EntityMnager
manager.close();
//關閉EnetityManagerFactory
factory.close();
}
}

JPA測試實例