Merge pull request #10219 from thejoeflow/BAEL-4635

[BAEL-4635] Tests for JPA Transient Annotation tutorial
This commit is contained in:
Jonathan Cook 2020-11-10 10:44:45 +01:00 committed by GitHub
commit 75a4c2e95d
5 changed files with 239 additions and 1 deletions

View File

@ -27,7 +27,21 @@
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate5</artifactId>
<version>2.9.8</version>
</dependency>
<!--Compile time JPA API -->
<dependency>
<groupId>javax.persistence</groupId>

View File

@ -0,0 +1,37 @@
package com.baeldung.ignorable.fields;
import java.util.Properties;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
public class HibernateConfig {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
Configuration configuration = new Configuration();
Properties settings = new Properties();
settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
settings.put(Environment.URL, "jdbc:mysql://localhost:3306/app_db?useSSL=false");
settings.put(Environment.USER, "root");
settings.put(Environment.PASS, "password");
settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
configuration.setProperties(settings);
configuration.addAnnotatedClass(User.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
}
}

View File

@ -0,0 +1,80 @@
package com.baeldung.ignorable.fields;
import java.io.Serializable;
import java.util.StringJoiner;
import javax.persistence.*;
@Entity
@Table(name = "Users")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String email;
private String password;
@Transient
private String currentDevice;
// Needed for Hibernate mapping
public User() {
}
public User(String email, String password, String currentDevice) {
this.email = email;
this.password = password;
this.currentDevice = currentDevice;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCurrentDevice() {
return currentDevice;
}
public void setCurrentDevice(String currentDevice) {
this.currentDevice = currentDevice;
}
@Override
public String toString() {
return new StringJoiner(", ", User.class.getSimpleName() + "[", "]").add("id=" + id)
.add("email='" + email + "'")
.add("password='" + password + "'")
.add("currentDevice='" + currentDevice + "'")
.toString();
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof User))
return false;
User user = (User) o;
return email.equals(user.email);
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.ignorable.fields;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class UserDao {
public void saveUser(User user) {
Transaction transaction = null;
try (Session session = HibernateConfig.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
session.save(user);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
}
}
public List<User> getUsers() {
try (Session session = HibernateConfig.getSessionFactory().openSession()) {
return session.createQuery("from User", User.class).list();
}
}
}

View File

@ -0,0 +1,79 @@
package com.baeldung.ignorable.fields;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.io.*;
import java.util.List;
import java.util.Random;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
public class TransientFieldUnitTest {
private final UserDao userDao = new UserDao();
private final int randInt = new Random().nextInt();
private final User user = new User("user" + randInt + "@bar.com", "hunter2", "MacOSX");
@Test
public void givenFieldWithTransientAnnotation_whenSavingViaJPA_thenFieldIgnored() {
userDao.saveUser(user);
List<User> allUsers = userDao.getUsers();
User savedUser = allUsers.get(allUsers.indexOf(user));
assertNull(savedUser.getCurrentDevice());
}
@Test
public void givenFieldWithTransientAnnotation_whenSerializingObject_thenFieldSerialized() throws IOException, ClassNotFoundException {
FileOutputStream fout = new FileOutputStream("test.obj");
ObjectOutputStream out = new ObjectOutputStream(fout);
out.writeObject(user);
out.flush();
out.close();
FileInputStream fin = new FileInputStream("test.obj");
ObjectInputStream in = new ObjectInputStream(fin);
User savedUser = (User) in.readObject();
in.close();
assertEquals(user.getCurrentDevice(), savedUser.getCurrentDevice());
}
@Test
public void givenFieldWithTransientAnnotation_whenSerializingToJSON_thenFieldSerialized() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(user);
User savedUser = objectMapper.readValue(json, User.class);
assertEquals(user.getCurrentDevice(), savedUser.getCurrentDevice());
}
@Test
public void givenJacksonHibernate5Module_whenSerializingTransientAnnotation_thenFieldIgnored() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new Hibernate5Module());
String json = objectMapper.writeValueAsString(user);
User savedUser = objectMapper.readValue(json, User.class);
assertNull(savedUser.getCurrentDevice());
}
@Test
public void givenPropagateTransientFieldFlag_whenSerializingTransientAnnotation_thenFieldSerialized() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true);
String json = objectMapper.writeValueAsString(user);
User savedUser = objectMapper.readValue(json, User.class);
assertEquals(user.getCurrentDevice(), savedUser.getCurrentDevice());
}
}