A Simple JPA 1.0

项目结构

src

-- JPATest.java

src -> model

-- Users.java

src -> META-INF

-- persistence.xml

 

LIbraries:

EclipseLink 2.1x

 

Code:

JPATest.java

import java.util.List;

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

import model.Users;

public class JPATest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPA_Test");
		EntityManager entityManger = emf.createEntityManager();
		System.out.println(entityManger.toString());
		
		//添加数据
		Users user = new Users();
		user.setName("Jim Green");
		user.setAge(6);
		EntityTransaction trans = entityManger.getTransaction();
		
		trans.begin();		
		entityManger.persist(user);		
		trans.commit();				
		
		//查询数据
		
		String queryString = "select * from users";
		Query query = entityManger.createNativeQuery(queryString,Users.class);
		@SuppressWarnings("unchecked")
		List users = query.getResultList();
		for(Users u : users){
			System.out.println(u.getName());
		}
		
		entityManger.close();
		
	}
}


Users.java

package model;

import java.io.Serializable;
import javax.persistence.*;


/**
 * The persistent class for the users database table.
 * 
 */
@Entity
@Table(name="users")
public class Users implements Serializable {
	private static final long serialVersionUID = 1L;
	private int id;
	private int age;
	private String name;

    public Users() {
    }


	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name = "id", unique=true, nullable=false)
	public int getId() {
		return this.id;
	}
	

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

	@Column(name = "age")
	public int getAge() {
		return this.age;
	}

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


	@Column(name = "name")
	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}
}


persistence.xml



	
		org.eclipse.persistence.jpa.PersistenceProvider
		model.Users
		
			
			
			
			
		
	


常见错误:

1、Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.sequence' doesn't exist

解决方法:

将strategy=GenerationType.AUTO修改为strategy=GenerationType.IDENTITY

 

2、during the execution of the query was detected to be null.  Primary keys must not contain null.

解决方法:

给实体类的每个属性的get方法上加@Column注解

 

你可能感兴趣的:(JPA)