一:jpa
java的一个规范。Java Persistence API ,其中有一些实现该规范的框架,比如Hibernate,openjpa,注意这里所说的和Spring没有任何关系。
简单实例:
1,放入jar openjpa-all-2.2.2.jar mysql-connector-java-5.1.15-bin.jar
2,src作为远吗目录
①:在src下有META-INF文件夹,其中有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" version="2.0">
<persistence-unit name="PersonService"
transaction-type="RESOURCE_LOCAL">
<provider>
org.apache.openjpa.persistence.PersistenceProviderImpl
</provider>
<class>com.w.Person</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mydb" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="wang" />
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
</properties>
</persistence-unit>
</persistence>
==
②:java代码
==
package com.w;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Id;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.Table;
public class Main {
public static void main(String[] args) {
// 创建EntityManagerFactory
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("PersonService");
// 创建EntityManager
EntityManager em = emf.createEntityManager();
// 查询Person
Person o = em.find(Person.class, 1);
System.out.println(o.getName());
// 插入Person
em.getTransaction().begin();
Person pp = new Person();
pp.setName("ccc");
em.persist(pp);
em.getTransaction().commit();
// 执行简单sql语句
Query q = em.createQuery("select p.name from Person p ");// 这里必须有别名
List<String> list = q.getResultList();
for (String name : list) {
System.out.println(name);
}
}
}
@Entity
@Table(name = "person")
class Person {
@Id
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
==
二:Spring。