结构~~~~~~~~~
/**
* 客户类
* @author Administrator
*
*/
@Entity
@Table(name="customers") //对应表名
public class Customer {
@Id
//指定主键生成策略(MSSQL,MYSQL --- identity, Oracle --- sequence)
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Column(name="name",length=20)
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
JPA 配置文件~~~~~~~~~~~~~~~~~~~~
<?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/SMLSchema-instance"
version="2.0">
<!-- transaction-type: JTA 分布式资源管理事务(多个数据库)
RESOURCE_LOCAL 本地资源管理事务,单个数据库
-->
<persistence-unit name="jpa" transaction-type="RESOURCE_LOCAL">
<!-- 供应商(指定具体的哪款产品) -->
<!-- 可以去掉,默认搜索/META-INF/services/javax.persistence.spi.PersistenceProvider -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<!-- 引入实体类 -->
<!-- 有注解@Entity后,可以去掉 -->
<class>jpa.persistence.Customer</class>
<!-- 指定具体的持久化产品自身的属性 -->
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/jpa"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="32147"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="none"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
测试~~~~~~~~~~~~~~~
public class AppTest {
public static void main(String[] args) {
// ########### 原 Hibernate 写法 ###############
// Configuration conf = new Configuration();
// SessionFactory sf = conf.configure().buildSessionFactory();
// Session s = sf.openSession();
// Transaction tx = s.beginTransaction();
// s.save(null);
// tx.commit();
// s.close();
//创建实体管理器工厂 === 相当于 sessionFactory
EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa");
//创建实体管理器 === 相当于session
EntityManager em = emf.createEntityManager();
//通过实体管理器获得事务对象
EntityTransaction tx = em.getTransaction();
tx.begin();
Customer c = new Customer();
c.setName("toma");
em.persist(c);
tx.commit();
em.close();
}
}