⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 customertest.java

📁 JPA入门文章源码
💻 JAVA
字号:
package entity;

import junit.framework.JUnit4TestAdapter;
import org.junit.After;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Before;
import org.junit.Test;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

/**
 * @author Antonio Goncalves
 */
public class CustomerTest {
    private static String PERSISTENCE_UNIT_NAME = "watermelonPU";

    private EntityManagerFactory emf;
    private EntityManager em;
    private EntityTransaction trans;

    public static junit.framework.Test suite() {
        return new JUnit4TestAdapter(CustomerTest.class);
    }

    @Before
    public void init() {
        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
        em = emf.createEntityManager();
        trans = em.getTransaction();
    }

    @After
    public void close() {
        em.close();
        emf.close();
    }

    @Test
    public void createCustomer() {
        Customer customer = new Customer(1L, "John", "Lennon", "+411909", "john@lenon.com", 66);

        // Persists a customer
        trans.begin();
        em.persist(customer);
        trans.commit();

        // Finds the customer by primary key
        customer = em.find(Customer.class, 1L);
        assertEquals(customer.getEmail(), "john@lenon.com");
        assertEquals("Age should be 66", customer.getAge(), 66);

        // Updates the customer
        trans.begin();
        customer.setEmail("john@beatles.co.uk");
        trans.commit();

        // Finds the customer by primary key
        customer = em.find(Customer.class, 1L);
        assertEquals(customer.getEmail(), "john@beatles.co.uk");
        assertEquals("Age should be 66", customer.getAge(), 66);

        // Deletes the customer
        trans.begin();
        em.remove(customer);
        trans.commit();

        assertNull("Customer should have been deleted", em.find(Customer.class, 1L));
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -