JPA小例
2747 ワード
:
package com.dada.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class UserBean {
private Integer id;
private String name;
public UserBean() {
super();
// TODO Auto-generated constructor stub
}
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
:
package com.dada.test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.dada.entity.UserBean;
public class Testgg {
private EntityManager em;
private EntityManagerFactory emf;
public Testgg() {
super();
emf = Persistence.createEntityManagerFactory("testJPAPU");
em = emf.createEntityManager();
}
public void add(UserBean bean) {
em.getTransaction().begin();
em.persist(bean);
em.getTransaction().commit();
}
public static void main(String[] args) {
UserBean ub = new UserBean();
ub.setName("dada");
UserBean ub1 = new UserBean();
ub1.setName(" ");
new Testgg().add(ub);
new Testgg().add(ub1);
}
}
persistence.xml :
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="testJPAPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.dada.entity.UserBean</class>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url"
value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="test" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
</persistence>