JPA系列二:基本使用

1、创建jpa项目
JPA系列二:基本使用_第1张图片
2、添加maven模块
JPA系列二:基本使用_第2张图片
3、删除lib文件夹。将META-INF移到resources里面。
JPA系列二:基本使用_第3张图片
4、引入依赖


    
    
        org.hibernate
        hibernate-entitymanager
        4.2.4.Final
    
    
    
        mysql
        mysql-connector-java
        5.1.17
    

5、创建实体类Customer

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

	private Integer id;
	private String lastName;
	private String email;
	private int age;
	
	public Customer() {
		// TODO Auto-generated constructor stub
	}
	
	public Customer(String lastName, int age) {
		super();
		this.lastName = lastName;
		this.age = age;
	}

	@GeneratedValue(strategy=GenerationType.AUTO)
	@Id
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@Column(name="LAST_NAME")
	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 int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
}

6、在persistence.xml中配置

 
     
     org.hibernate.ejb.HibernatePersistence

     
     com.atguigu.jpa.helloworld.Customer

     
         
         
         
         
         

         
         
         
         
     
 

7、编写方法测试

public static void main(String[] args) {
	//1. 创建 EntitymanagerFactory
	String persistenceUnitName = "NewPersistenceUnit";
	EntityManagerFactory entityManagerFactory = 
			Persistence.createEntityManagerFactory(persistenceUnitName);
			
	//2. 创建 EntityManager
	EntityManager entityManager = entityManagerFactory.createEntityManager();
	
	//3. 开启事务
	EntityTransaction transaction = entityManager.getTransaction();
	transaction.begin();
	
	//4. 进行持久化操作
	Customer customer = new Customer();
	customer.setAge(12);
	customer.setEmail("[email protected]");
	customer.setLastName("Tom");
	entityManager.persist(customer);

	//5. 提交事务
	transaction.commit();
	
	//6. 关闭 EntityManager
	entityManager.close();
	
	//7. 关闭 EntityManagerFactory
	entityManagerFactory.close();
}

控制台输出:
JPA系列二:基本使用_第4张图片
测试成功后会在数据库自动创建表jpa_cutomers。并插入数据
在这里插入图片描述

你可能感兴趣的:(JPA)