Maven+Hibernate+jpa环境搭建
Posted 萌萌的小二逼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Maven+Hibernate+jpa环境搭建相关的知识,希望对你有一定的参考价值。
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();
}
}
执行测试方法,完成测试:
然后查看数据库就可以看到插入的数据:
至此,完成!!!!
以上是关于Maven+Hibernate+jpa环境搭建的主要内容,如果未能解决你的问题,请参考以下文章
JPA---Spring-data-JPA---Hibernate