JPA环境的搭建

persistence.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
	xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
	<persistence-unit name="JPA-1" transaction-type="RESOURCE_LOCAL">
		<!--配置什么ORM产品作为JPA的实现 -->
		<provider> org.hibernate.ejb.HibernatePersistence</provider>
		<!--持久化信息 -->
		<class>com.test.model.Custerm</class>

		<properties>
			<!--连接数据库的基本信息 -->
			<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
			<property name="javax.persistence.jdbc.url" value="jdbc:mysql:///jpa" />
			<property name="javax.persistence.jdbc.user" value="root" />
			<property name="javax.persistence.jdbc.password" value="root" />

			<!--配置JPA信息 实际是Hibernate信息 -->
			<property name="hinernate.format_sql" value="true" />
			<property name="hibernate.show_sql" value="true" />
			<property name="hibernate.hbm2ddl.auto" value="update" />
		</properties>
	</persistence-unit>
</persistence>

Custerm.java
package com.test.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Table(name="JPA_CUSTERM")
@Entity
public class Custerm {
	private Integer id;
	private String name;
	private int age;
	
	@Column(name="ID")
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Id
	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 int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}
Main.java
package com.test.test;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import com.test.model.Custerm;

public class Main {

	public static void main(String[] arg){
		//1.获取Jpa单元的名称
		String persistenceUnitName="JPA-1";
		//2.创建EntityManagerfactory
		EntityManagerFactory emf=Persistence.createEntityManagerFactory(persistenceUnitName);
		//3创建EntityManager
		EntityManager em=emf.createEntityManager();
		//4.开启事务
		EntityTransaction entityTransaction =em.getTransaction();
		entityTransaction.begin();
		//5.进行持久化操作
		Custerm cs=new Custerm();
		cs.setAge(12);
		cs.setName("IT1");
		
		//6.进行保存
		em.persist(cs);
		//7.提交事务
		entityTransaction.commit();
		//8.关闭EntityManager
		em.close();
		//9.关闭EntityManagerFactory
		emf.close();
		
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值