|
| 1 | +package com.baeldung.hibernate.converter; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | + |
| 5 | +import org.hibernate.Session; |
| 6 | +import org.hibernate.Transaction; |
| 7 | +import org.junit.After; |
| 8 | +import org.junit.Before; |
| 9 | +import org.junit.Test; |
| 10 | + |
| 11 | +import com.baeldung.hibernate.HibernateUtil; |
| 12 | +import com.baeldung.hibernate.pojo.Person; |
| 13 | +import com.baeldung.hibernate.pojo.PersonName; |
| 14 | +import com.vividsolutions.jts.util.Assert; |
| 15 | + |
| 16 | +public class PersonNameConverterTest { |
| 17 | + |
| 18 | + private Session session; |
| 19 | + private Transaction transaction; |
| 20 | + |
| 21 | + @Before |
| 22 | + public void setUp() throws IOException { |
| 23 | + session = HibernateUtil.getSessionFactory() |
| 24 | + .openSession(); |
| 25 | + transaction = session.beginTransaction(); |
| 26 | + |
| 27 | + session.createNativeQuery("delete from personTable") |
| 28 | + .executeUpdate(); |
| 29 | + |
| 30 | + transaction.commit(); |
| 31 | + transaction = session.beginTransaction(); |
| 32 | + } |
| 33 | + |
| 34 | + @After |
| 35 | + public void tearDown() { |
| 36 | + transaction.rollback(); |
| 37 | + session.close(); |
| 38 | + } |
| 39 | + |
| 40 | + @Test |
| 41 | + public void givenPersonName_WhenSaving_ThenNameAndSurnameConcat() { |
| 42 | + final String name = "name"; |
| 43 | + final String surname = "surname"; |
| 44 | + |
| 45 | + PersonName personName = new PersonName(); |
| 46 | + personName.setName(name); |
| 47 | + personName.setSurname(surname); |
| 48 | + |
| 49 | + Person person = new Person(); |
| 50 | + person.setPersonName(personName); |
| 51 | + |
| 52 | + Long id = (Long) session.save(person); |
| 53 | + |
| 54 | + session.flush(); |
| 55 | + session.clear(); |
| 56 | + |
| 57 | + String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id") |
| 58 | + .setParameter("id", id) |
| 59 | + .getSingleResult(); |
| 60 | + |
| 61 | + Assert.equals(surname + ", " + name, dbPersonName); |
| 62 | + |
| 63 | + Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class) |
| 64 | + .setParameter("id", id) |
| 65 | + .getSingleResult(); |
| 66 | + |
| 67 | + Assert.equals(dbPerson.getPersonName() |
| 68 | + .getName(), name); |
| 69 | + Assert.equals(dbPerson.getPersonName() |
| 70 | + .getSurname(), surname); |
| 71 | + } |
| 72 | + |
| 73 | +} |
0 commit comments