首页 > 代码库 > jpa入门案例
jpa入门案例
1.1. 新建一个java工程jpaDemo1
1.2. 在工程下新建一个lib文件夹,用来存放jar包
1.3. 引入下面的jar包
所使用hibernat版本:hibernate-release-4.3.7.Final
Lib\jpa目录和lib\required目录下所有的jar包,mysql驱动包
1.4. Src下新建META-INF目录
1.5. META-INF目录下新建persistence.xml
persistence.xml |
<?xmlversion="1.0"encoding="UTF-8"?> <persistencexmlns="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指定持久化单元的名字 transaction-type指定事务类型为本地事务 --> <persistence-unitname="jpaDemo"transaction-type="RESOURCE_LOCAL"> <properties> <propertyname="hibernate.dialect"value="org.hibernate.dialect.MySQL5Dialect"/> <propertyname="hibernate.connection.driver_class"value="com.mysql.jdbc.Driver"/> <propertyname="hibernate.connection.username"value="root"/> <propertyname="hibernate.connection.password"value="root"/> <propertyname="hibernate.connection.url"value="jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=UTF-8"/> <propertyname="hibernate.hbm2ddl.auto"value="update"/> <propertyname="hibernate.show_sql"value="true"/> </properties> </persistence-unit> </persistence>
|
1.6. 新建实体类Person.java
Person.java |
package com.morris.entity;
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id;
@Entity public class Person {
@Id @GeneratedValue private Integerid;
private Stringname;
private Integerage;
public Integer getId() { returnid; }
public void setId(Integer id) { this.id = id; }
public String getName() { returnname; }
public void setName(String name) { this.name = name; }
public Integer getAge() { returnage; }
public void setAge(Integer age) { this.age = age; }
public Person( String name, Integer age) { super(); this.name = name; this.age = age; }
public Person() { super(); // TODO Auto-generated constructor stub }
@Override public String toString() { return"Person [id=" + id +", name=" + name +", age=" + age +"]"; }
}
|
1.7. 新建测试类TestPerson.java
TestPerson.java |
package com.morris.entity;
import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence;
import org.junit.Test;
public class TestPerson {
@Test public void save() {
//实体管理工厂类 jpaDemo为配置文件中持久化单元名 EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpaDemo"); //尸体管理器 EntityManager manager = factory.createEntityManager();
//开始事务 manager.getTransaction().begin(); //持久化person对象 manager.persist(new Person("morris", 22));
//提交事务 manager.getTransaction().commit();
//关闭资源 manager.close();
factory.close();
}
}
|
1.8. 运行结果
后台打印sql语句: |
Hibernate: insert into Person (age, name) values (?, ?) |
jpa入门案例