Merge pull request #6989 from liesheng/BAEL-2931

sample code for article "Java Optional As Return Type"
This commit is contained in:
rpvilao 2019-06-03 20:41:26 +02:00 committed by GitHub
commit e2394d27af
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 320 additions and 1 deletions

View File

@ -22,6 +22,9 @@
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<icu.version>64.2</icu.version>
<hibernate.core.version>5.4.0.Final</hibernate.core.version>
<h2database.version>1.4.197</h2database.version>
<jackson.databind.version>2.9.8</jackson.databind.version>
</properties>
<dependencies>
@ -30,7 +33,21 @@
<artifactId>icu4j</artifactId>
<version>${icu.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.core.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2database.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.databind.version}</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,41 @@
package com.baeldung.optionalReturnType;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class HandleOptionalTypeExample {
static Map<String, User> usersByName = new HashMap();
static {
User user1 = new User();
user1.setUserId(1l);
user1.setFirstName("baeldung");
usersByName.put("baeldung", user1);
}
public static void main(String[] args) {
changeUserName("baeldung", "baeldung-new");
changeUserName("user", "user-new");
}
public static void changeUserName(String oldFirstName, String newFirstName) {
Optional<User> userOpt = findUserByName(oldFirstName);
if (userOpt.isPresent()) {
User user = userOpt.get();
user.setFirstName(newFirstName);
System.out.println("user with name " + oldFirstName + " is changed to " + user.getFirstName());
} else {
// user is missing
System.out.println("user with name " + oldFirstName + " is not found.");
}
}
public static Optional<User> findUserByName(String name) {
// look up the user in the database, the user object below could be null
User user = usersByName.get(name);
Optional<User> opt = Optional.ofNullable(user);
return opt;
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.optionalReturnType;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class OptionalToJsonExample {
public static void main(String[] args) {
UserOptional user = new UserOptional();
user.setUserId(1l);
user.setFirstName("Bael Dung");
ObjectMapper om = new ObjectMapper();
try {
System.out.print("user in json is:" + om.writeValueAsString(user));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.optionalReturnType;
import java.util.Optional;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class PersistOptionalTypeExample {
static String persistenceUnit = "com.baeldung.optionalReturnType";
static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);
static EntityManager entityManager = emf.createEntityManager();
// to run this app, uncomment the follow line in META-INF/persistence.xml
// <class>com.baeldung.optionalReturnType.UserOptionalField</class>
public static void main(String[] args) {
UserOptionalField user1 = new UserOptionalField();
user1.setUserId(1l);
user1.setFirstName(Optional.of("Bael Dung"));
entityManager.persist(user1);
UserOptional user2 = entityManager.find(UserOptional.class, 1l);
System.out.print("User2.firstName:" + user2.getFirstName());
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.optionalReturnType;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class PersistOptionalTypeExample2 {
static String persistenceUnit = "com.baeldung.optionalReturnType";
static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);
static EntityManager em = emf.createEntityManager();
public static void main(String[] args) {
UserOptional user1 = new UserOptional();
user1.setUserId(1l);
user1.setFirstName("Bael Dung");
em.persist(user1);
UserOptional user2 = em.find(UserOptional.class, 1l);
System.out.print("User2.firstName:" + user2.getFirstName());
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.optionalReturnType;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class PersistUserExample {
static String persistenceUnit = "com.baeldung.optionalReturnType";
static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);
static EntityManager em = emf.createEntityManager();
public static void main(String[] args) {
User user1 = new User();
user1.setUserId(1l);
user1.setFirstName("Bael Dung");
em.persist(user1);
User user2 = em.find(User.class, 1l);
System.out.print("User2.firstName:" + user2.getFirstName());
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.optionalReturnType;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Optional;
public class SerializeOptionalTypeExample {
public static void main(String[] args) {
User user1 = new User();
user1.setUserId(1l);
user1.setFirstName("baeldung");
serializeObject(user1, "user1.ser");
UserOptionalField user2 = new UserOptionalField();
user2.setUserId(1l);
user2.setFirstName(Optional.of("baeldung"));
serializeObject(user2, "user2.ser");
}
public static void serializeObject(Object object, String fileName) {
// Serialization
try {
FileOutputStream file = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(object);
out.close();
file.close();
System.out.println("Object " + object.toString() + " has been serialized to file " + fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.optionalReturnType;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class User implements Serializable {
@Id
private long userId;
private String firstName;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.optionalReturnType;
import java.io.Serializable;
import java.util.Optional;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class UserOptional implements Serializable {
@Id
private long userId;
@Column(nullable = true)
private String firstName;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public Optional<String> getFirstName() {
return Optional.ofNullable(firstName);
}
public void setFirstName(String firstName) {
this.firstName = firstName;
Optional.ofNullable(firstName);
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.optionalReturnType;
import java.io.Serializable;
import java.util.Optional;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class UserOptionalField implements Serializable {
@Id
private long userId;
private Optional<String> firstName;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public Optional<String> getFirstName() {
return firstName;
}
public void setFirstName(Optional<String> firstName) {
this.firstName = firstName;
}
}

View File

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit
name="com.baeldung.optionalReturnType"
transaction-type="RESOURCE_LOCAL">
<description>Persist Optional Return Type Demo</description>
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.optionalReturnType.User</class>
<class>com.baeldung.optionalReturnType.UserOptional</class>
<!--
<class>com.baeldung.optionalReturnType.UserOptionalField</class>
-->
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver"
value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:h2:mem:test" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="show_sql" value="true" />
<property name="hibernate.temp.use_jdbc_metadata_defaults"
value="false" />
</properties>
</persistence-unit>
</persistence>