ddl语句
CREATE TABLE `t_user` (
`id` varchar(32) NOT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
User
package com.jege.jpa.primary;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
/**
* @author JE哥
* @email 1272434821@qq.com
* @description:jpa-uuid主键生成策略
*/
@Entity
@Table(name = "t_user")
@GenericGenerator(name = "jpa-uuid", strategy = "uuid")
public class User {
@Id
@GeneratedValue(generator = "jpa-uuid")
@Column(length = 32)
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
MainTest
package com.jege.jpa.primary;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* @author JE哥
* @entityManagerail 1272434821@qq.com
* @description:jpa-uuid主键生成测试
*/
public class MainTest {
private static EntityManagerFactory entityManagerFactory = null;
private EntityManager entityManager = null;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
entityManagerFactory = Persistence.createEntityManagerFactory("com.jege.jpa");
}
@Before
public void setUp() throws Exception {
entityManager = entityManagerFactory.createEntityManager();
}
@Test
public void persist() throws Exception {
User user = new User();
user.setName("jege");
entityManager.getTransaction().begin();
entityManager.persist(user);
entityManager.getTransaction().commit();
}
@After
public void tearDown() throws Exception {
if (entityManager != null && entityManager.isOpen()) {
entityManager.close();
}
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
if (entityManagerFactory != null && entityManagerFactory.isOpen()) {
entityManagerFactory.close();
}
}
}
源码地址
如果觉得我的文章或者代码对您有帮助,可以请我喝杯咖啡。您的支持将鼓励我继续创作!谢谢!