@Entity
public class User {
@Id
private Long id;
private String name;
// Getters and setters
}
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
version="2.2">
<persistence-unit name="myPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.example.User</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/mydb"/>
<property name="javax.persistence.jdbc.user" value="username"/>
<property name="javax.persistence.jdbc.password" value="password"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
</properties>
</persistence-unit>
</persistence>
EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit");
EntityManager em = emf.createEntityManager();
User user = em.find(User.class, 1L);
em.getTransaction().begin();
user.setName("NewName");
em.getTransaction().commit();
em.getTransaction().begin();
User newUser = new User();
newUser.setId(2L);
newUser.setName("John");
em.persist(newUser);
em.getTransaction().commit();
em.getTransaction().begin();
User deleteUser = em.find(User.class, 2L);
em.remove(deleteUser);
em.getTransaction().commit();
em.close();
emf.close();