Hibernate5+maven+jpa 框架搭建
阿新 • • 發佈:2019-02-17
1、新建一個Maven專案
2、配置pom:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.hibernate.version>5.2.10.Final</project.hibernate.version>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId><artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${project.hibernate.version}</version></dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${project.hibernate.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
3、在resources/META-INF資料夾下新建hibernate配置檔案persistence.xml:
<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_2_0.xsd"
version="2.0">
<persistence-unit name="myjpa">
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/test" />
<property name="javax.persistence.jdbc.user"
value="root" />
<property name="javax.persistence.jdbc.password"
value="123456" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
4、測試:
新建一個實體類User:
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="user")
@Data
public class User {
@Id @GeneratedValue
private int id;
private String name;
}
測試類UserTest:
public class UserTest extends TestCase {
EntityManagerFactory factory;
@Override
protected void setUp() throws Exception {
//初始化
factory= Persistence.createEntityManagerFactory("myjpa");
}
/**測試新增一條資料 */
public void testSave(){
EntityManager manager=factory.createEntityManager();
manager.getTransaction().begin();
User user=new User();
user.setName("萌萌的小二逼");
manager.persist(user);
manager.getTransaction().commit();
manager.close();
factory.close();
}
}
執行測試方法,完成測試:
然後檢視資料庫就可以看到插入的資料:
至此,完成!!!!