// Get an EntityManager instance EntityManager entityManager = entityManagerFactory.createEntityManager(); // Get a reference to the User entity with ID 1 User user = entityManager.getReference(User.class, 1L); // Accessing any property of the user will now load its data from the database System.out.println(user.getName());
// Get an EntityManager instance EntityManager entityManager = entityManagerFactory.createEntityManager(); // Create a new order and set its customer to a reference to an existing Customer entity Order order = new Order(); Customer customer = entityManager.getReference(Customer.class, 2L); order.setCustomer(customer); // Persist the order entityManager.getTransaction().begin(); entityManager.persist(order); entityManager.getTransaction().commit();In this example, a new Order entity is created and its customer property is set to a reference to an existing Customer entity with ID 2. Because the customer reference is not actually loaded from the database, this can be a more efficient way to work with entity relationships. The javax.persistence package is part of the Java Persistence API (JPA) library.