JPA(Java Persistence API,Java持久化API),定义了对象-关系映射(ORM)以及实体对象持久化的标准接口
JPA介绍:
转载地址:http://blog.csdn.net/elementf/article/details/72674926
META-INF 文件下 persistence.xml 配置文件
<?xml version="1.0"?>
<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="jpaDemo" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="123"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/usermanager?useUnicode=true&characterEncoding=UTF-8"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
model bean 类:
@Entity //实体关系映射
@Table(name="user") //数据库表名
public class User {
@Id // ID生成策略
@GeneratedValue(strategy = GenerationType.TABLE)
//GeneratorType.AUTO ,由JPA自动生成
//GenerationType.SEQUENCE,使用数据库的序列号,需要数据库的支持(如Oracle)
//GenerationType.IDENTITY,使用数据库的自增长字段,需要数据库的支持(如SQL Server、MySQL、DB2、Derby等)
//GenerationType.TABLE,使用指定的数据库表记录ID的增长 需要定义一个TableGenerator,在@GeneratedValue中引用。
@Column(name="id") //数据库字段
private int id; // ID
@Column(name="name")
private String name; // 姓名
@Column(name="age")
private int age; // 年龄
ublic class AppTest {
public Log log = LogFactory.getLog(AppTest.class);
private EntityManager em;
@Before
public void before() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpaDemo");
em = factory.createEntityManager();
em.getTransaction().begin();// 开始事物
}
@After
public void after() {
em.getTransaction().commit();
em.close();
}
@Test
public void addUser(){
User user = new User("张三",23,0,"zhang.jpg");
em.persist(user);
}
@Test
public void getUser(){
User user = em.find(User.class, 6);
log.info(user.toString());
}