A Simple JPA 1.0

3530 ワード

プロジェクト構造
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注記を付ける