JPA之HelloWorld

第一步:创建一个web项目,导入相关的Jar包。

第二步:在src下新建META-INF/persistence.xml文件。

第三步:创建实体类(Person.java) 。

第四步:编写测试。

全部代码如下:

 

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"
	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="person" 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="root" />
			<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/mydb" />
			<property name="hibernate.max_fetch_depth" value="5" />
			<property name="hibernate.jdbc.fetch_size" value="20" />
			<property name="hibernate.jdbc.batch_size" value="10" />

			<property name="hibernate.hbm2ddl.auto" value="update" />
			<property name="hibernate.show_sql" value="true" />
			<property name="hibernate.format_sql" value="false" />
		</properties>
	</persistence-unit>
</persistence>

 

Person.java

 

 

package domain;

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

@Entity
@Table(name="person")
public class Person {
	private Integer id;
	private String name;
	
	public Person(String name) {
		super();
		this.name = name;
	}
	public Person() {
		super();
	}
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	@Column(name="name")
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	
}

 

测试类

 

 

package test;

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

import org.junit.Test;

import domain.Person;

public class PersonTest {

	@Test
	public void save(){
		EntityManagerFactory factory = Persistence.createEntityManagerFactory("person");
		EntityManager em = factory.createEntityManager();
		em.getTransaction().begin();
		em.persist(new Person("HelloWorld"));
		em.getTransaction().commit();
		em.close();
		factory.close();
	}
}

你可能感兴趣的:(xml,Hibernate,mysql,jdbc,jpa)