Jpa到Spring data jpa

一: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。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值