Description: Hibernate Types is a set of extra types not supported by default in Hibernate Core. One of these types is java.time.YearMonth
. This is a Spring Boot application that uses Hibernate Type to store this YearMonth
in a MySQL database as integer or date.
Key points:
- for Maven, add Hibernate Types as a dependency in
pom.xml
- in entity use
@TypeDef
to maptypeClass
todefaultForType
Book.java
@Data
@Entity
@TypeDef(
typeClass = YearMonthIntegerType.class, // or, YearMonthDateType
defaultForType = YearMonth.class
)
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String isbn;
private YearMonth releaseDate;
}
BookRepository.java
@Repository
public interface BookRepository extends JpaRepository<Book, Long> {
Book findByTitle(String title);
}
BookStoreService.java
@RequiredArgsConstructor
@Service
public class BookstoreService {
private final BookRepository bookRepository;
public void newBook() {
Book book = new Book();
book.setIsbn("001");
book.setTitle("Young Boy");
book.setReleaseDate(YearMonth.now());
bookRepository.save(book);
}
public void displayBook() {
Book book = bookRepository.findByTitle("Young Boy");
System.out.println(book);
}
}
MainApp.java
@RequiredArgsConstructor
@SpringBootApplication
public class MainApplication {
private final BookstoreService bookstoreService;
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Bean
public ApplicationRunner init() {
return args -> {
bookstoreService.newBook();
bookstoreService.displayBook();
};
}
}
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredb?createDatabaseIfNotExist=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.open-in-view=false
Console Output —
Hibernate: select book0_.id as id1_0_, book0_.isbn as isbn2_0_, book0_.release_date as release_3_0_, book0_.title as title4_0_ from book book0_ where book0_.title=?
Book(id=1, title=Young Boy, isbn=001, releaseDate=2021-06)