Home > AI > Backend > SpringBoot > mysql-connector-java >

Session CRUD

Example

Person.java

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;

    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
    private List<Address> addresses;
}

Address.java

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
public class Address {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String street;
    private int houseNumber;
    private String city;
    private int zipCode;

    @ManyToOne(fetch = FetchType.LAZY)
    private Person person;
}

TestSessionCRUD.java

import lombok.extern.slf4j.Slf4j;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.resource.transaction.spi.TransactionStatus;
import org.junit.jupiter.api.Test;
import org.springframework.security.core.parameters.P;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

/**
 * @description
 */




@Slf4j
public class TestSessionCRUD {



    /******************************
     * Preparations
     *****************************/
    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new Configuration()
                    .configure()
                    .buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }


    /******************************
     * Tests
     *****************************/



    @Test
    public void test_save() {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();


        Person person = Person.builder()
                .name("mary")
                .build();
        Address address = Address.builder()
                .person(person)
                .houseNumber(30)
                .build();
        person.setAddresses(Arrays.asList(address));

        // save both entities
        session.save(person);
//        session.flush();
        transaction.commit();


        Address dbAddress = session.find(Address.class, address.getId());
        Person dbPerson = dbAddress.getPerson();

        assertNotNull(dbPerson);
        assertNotNull(dbAddress);
        log.info("[Shark] ");

        session.clear();
        session.close();
    }



    @Test
    public void test_get_all() {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();


        // save the entity
        Person person = Person.builder()
                .name("mary")
                .build();
        Address address = Address.builder()
                .person(person)
                .houseNumber(30)
                .build();
        person.setAddresses(Arrays.asList(address));

        // save both entities
        session.save(person);
        transaction.commit();



        // get the entity numbers
        try {
            List <Person> persons = session.createQuery("from Person", Person.class).list();
            assertEquals(1, persons.size());
            assertEquals("mary", persons.get(0).getName());
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }


    /**
     * Read
     */

    @Test
    public void test_read_get() {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();


        // save the entity
        Person person = Person.builder()
                .name("mary")
                .build();
        Address address = Address.builder()
                .person(person)
                .houseNumber(30)
                .build();
        person.setAddresses(Arrays.asList(address));

        // save both entities
        session.save(person);
        transaction.commit();



        try {
            Person p = session.get(Person.class, person.getId());
            assertEquals("mary", p.getName());
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }



    @Test
    public void test_read_load() {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();


        // save the entity
        Person person = Person.builder()
                .name("mary")
                .build();
        Address address = Address.builder()
                .person(person)
                .houseNumber(30)
                .build();
        person.setAddresses(Arrays.asList(address));

        // save both entities
        session.save(person);
        transaction.commit();



        try {
            Person p = session.load(Person.class, person.getId());
            assertEquals("mary", p.getName());
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }




    @Test
    public void test_read_ById() {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();


        // save the entity
        Person person = Person.builder()
                .name("mary")
                .build();
        Address address = Address.builder()
                .person(person)
                .houseNumber(30)
                .build();
        person.setAddresses(Arrays.asList(address));

        // save both entities
        session.save(person);
        transaction.commit();
        session.close();





        Session s = sessionFactory.openSession();
        try {
            Person p = s.byId(Person.class).getReference(person.getId());
            assertEquals("mary", p.getName());
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }


    /**
     * Update
     */
    @Test
    public void test_saveUpdate() {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();


        // 1 - create entities
        Person person = Person.builder()
                .name("mary")
                .build();
        Address address = Address.builder()
                .person(person)
                .houseNumber(30)
                .build();
        person.setAddresses(Arrays.asList(address));


        // 2 - save both entities
        session.save(person);
        if (transaction.getStatus().equals(TransactionStatus.ACTIVE)) {
            transaction.commit();
        } else {
            transaction = session.beginTransaction();
            transaction.commit();
        }


        // 3 - get the entity
        Person p = session.load(Person.class, person.getId());
        assertEquals("mary", p.getName());


        // 4 - update the entity
        p.setName("peter");
        session.saveOrUpdate(p);
        if (transaction.getStatus().equals(TransactionStatus.ACTIVE)) {
            transaction.commit();
        } else {
            transaction = session.beginTransaction();
            transaction.commit();
        }


        // 5 - validate
        Person p2 = session.load(Person.class, p.getId());
        assertEquals("peter", p2.getName());

    }


    /**
     * Delete
     */
    @Test
    public void test_delete() {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();


        // 1 - create entities
        Person person = Person.builder()
                .name("mary")
                .build();
        Address address = Address.builder()
                .person(person)
                .houseNumber(30)
                .build();
        person.setAddresses(Arrays.asList(address));


        // 2 - save both entities
        session.save(person);
        if (transaction.getStatus().equals(TransactionStatus.ACTIVE)) {
            transaction.commit();
        } else {
            transaction = session.beginTransaction();
            transaction.commit();
        }


        // 4 - delete the entity

        session.delete(person);
        if (transaction.getStatus().equals(TransactionStatus.ACTIVE)) {
            transaction.commit();
        } else {
            transaction = session.beginTransaction();
            transaction.commit();
        }




        // 5 - validate
        try {
            Person p2 = session.load(Person.class, person.getId());
        } catch (Exception e){
            assertInstanceOf(ObjectNotFoundException.class, e);
        }

    }





    @Test
    public void test_remove() {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();


        // 1 - create entities
        Person person = Person.builder()
                .name("mary")
                .build();
        Address address = Address.builder()
                .person(person)
                .houseNumber(30)
                .build();
        person.setAddresses(Arrays.asList(address));


        // 2 - save both entities
        session.save(person);
        if (transaction.getStatus().equals(TransactionStatus.ACTIVE)) {
            transaction.commit();
        } else {
            transaction = session.beginTransaction();
            transaction.commit();
        }


        // 4 - delete the entity

        session.remove(person);
        if (transaction.getStatus().equals(TransactionStatus.ACTIVE)) {
            transaction.commit();
        } else {
            transaction = session.beginTransaction();
            transaction.commit();
        }




        // 5 - validate
        try {
            Person p2 = session.load(Person.class, person.getId());
        } catch (Exception e){
            assertInstanceOf(ObjectNotFoundException.class, e);
        }

    }
}

resources/hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">create-drop</property>


        <!-- JDBC connection pool (use the built-in) -->
        <property name="hibernate.connection.pool_size">100</property>

        <!-- Disable the second-level cache -->
        <property name="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</property>




        <mapping class="com.example.demo11.Person" />
        <mapping class="com.example.demo11.Address" />




    </session-factory>

</hibernate-configuration>

Leave a Reply