You should include both @Transien
t and transien
t.
Example
User.java
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "Users")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String email;
private String password;
@Transient
private transient Date loginTime;
}
UserRepository.java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
TestRepository.java
@SpringBootTest
class TestRepository {
@Autowired
UserRepository userRepository;
@BeforeEach
public void init() {
userRepository.deleteAll();
}
@Test
public void testTransient() {
User u = new User();
u.setEmail("test@fengcaoculture.com");
u.setLoginTime(new Date());
userRepository.save(u);
Assert.assertEquals(1, userRepository.findAll().size());
try {
// the proxy object of User is not working
// since the field of loginTime is NOT in the database
Object o = userRepository.getById(u.getId());
System.out.println("[Shark]" + o);
} catch (Exception e){
Assert.assertTrue(e instanceof LazyInitializationException);
}
}
@Test
public void test_serializable() throws IOException, ClassNotFoundException {
User u = new User();
u.setEmail("test@fengcaoculture.com");
u.setLoginTime(new Date());
// write to file
FileOutputStream fileOutputStream = new FileOutputStream("person.txt");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(u);
objectOutputStream.flush();
objectOutputStream.close();
FileInputStream fileInputStream = new FileInputStream("person.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
User u2 = (User) objectInputStream.readObject();
objectInputStream.close();
assertTrue(u2.getEmail().equals(u.getEmail()));
assertNull(u2.getLoginTime());
}
}
resources/application.properties
server.port = 8888
##################
# Mysql
##################
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
spring.jpa.show-sql= false