Skip to content

Commit

Permalink
chore: add jakarta data example
Browse files Browse the repository at this point in the history
  • Loading branch information
hantsy committed Jun 1, 2024
1 parent 9be9e38 commit 221be33
Show file tree
Hide file tree
Showing 8 changed files with 67 additions and 36 deletions.
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
name: jakartaee-data
name: jakarta-data

on:
push:
paths:
- "jakartaee-data/**"
- "jakarta-data/**"
branches:
- master
pull_request:
paths:
- "jakartaee-data/**"
- "jakarta-data/**"
types:
- opened
- synchronize
Expand All @@ -27,6 +27,6 @@ jobs:
cache: "maven"

- name: Build with Maven
run: mvn -B -q clean test --file jakartaee-data/pom.xml
run: mvn -B -q clean test --file jakarta-data/pom.xml


10 changes: 5 additions & 5 deletions jakarta-data/src/main/java/com/example/demo/Blogger.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@
public interface Blogger {

@Query("""
select p.id, p.title from Post p
where p.status = 'PUBLISHED'
order by p.createdAt desc
SELECT p.id, p.title FROM Post p
WHERE p.status = 'PUBLISHED'
ORDER BY p.createdAt DESC
""")
List<PostSummary> allPublished();
List<PostSummary> allPublishedPosts();

@Insert
void newPost(Post post);
Post newPost(Post post);
}
7 changes: 4 additions & 3 deletions jakarta-data/src/main/java/com/example/demo/DataConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,18 @@

import com.example.demo.repository.PostRepository;
import com.example.demo.repository.PostRepository_;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;

@Configuration
public class DataConfig {

@Bean
public StatelessSession statelessSession(LocalSessionFactoryBean sessionFactoryBean) {
return sessionFactoryBean.getObject().openStatelessSession();
public StatelessSession statelessSession(LocalContainerEntityManagerFactoryBean entityManagerFactoryBean) {
return entityManagerFactoryBean.getObject().unwrap(SessionFactory.class).openStatelessSession();
}

@Bean
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
package com.example.demo;

import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;
import java.util.Properties;


@Configuration
@EnableTransactionManagement
@PropertySource(value = "classpath:/hibernate.properties", ignoreResourceNotFound = true)
public class HibernateConfig {
@PropertySource(value = "classpath:/jpa.properties", ignoreResourceNotFound = true)
public class JpaConfig {

private static final String ENV_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String ENV_HIBERNATE_HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";
Expand All @@ -28,15 +30,16 @@ public class HibernateConfig {
private Environment env;

@Bean
public LocalSessionFactoryBean localSessionFactoryBean(DataSource dataSource) {
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setPackagesToScan("com.example.demo");
factoryBean.setHibernateProperties(hibernateProperties());
return factoryBean;
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource);
emf.setPackagesToScan("com.example.demo");
emf.setPersistenceProvider(new HibernatePersistenceProvider());
emf.setJpaProperties(jpaProperties());
return emf;
}

private Properties hibernateProperties() {
private Properties jpaProperties() {
Properties extraProperties = new Properties();
extraProperties.put(ENV_HIBERNATE_FORMAT_SQL, env.getProperty(ENV_HIBERNATE_FORMAT_SQL));
extraProperties.put(ENV_HIBERNATE_SHOW_SQL, env.getProperty(ENV_HIBERNATE_SHOW_SQL));
Expand All @@ -48,8 +51,12 @@ private Properties hibernateProperties() {
}

@Bean
public PlatformTransactionManager transactionManager(LocalSessionFactoryBean localSessionFactoryBean) {
return new HibernateTransactionManager(localSessionFactoryBean.getObject());
public PlatformTransactionManager transactionManager(LocalContainerEntityManagerFactoryBean entityManagerFactoryBean) {
return new JpaTransactionManager(entityManagerFactoryBean.getObject());
}

@Bean
public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) {
return new TransactionTemplate(transactionManager);
}
}
7 changes: 2 additions & 5 deletions jakarta-data/src/main/java/com/example/demo/model/Post.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.GenericGenerator;

import java.io.Serializable;
Expand Down Expand Up @@ -35,11 +36,7 @@ public class Post implements Serializable {
private Status status = Status.DRAFT;

@Column(name = "created_at")
@CreationTimestamp
private LocalDateTime createdAt;

@PrePersist // prepersist callback
public void beforePersist() {
this.setCreatedAt(LocalDateTime.now());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
import com.example.demo.model.Post;
import com.example.demo.model.Status;
import jakarta.data.repository.CrudRepository;
import jakarta.data.repository.Delete;
import jakarta.data.repository.Find;
import jakarta.data.repository.OrderBy;
import jakarta.data.repository.Query;
import jakarta.transaction.Transactional;

import java.util.List;
import java.util.UUID;
Expand All @@ -17,6 +18,7 @@ public interface PostRepository extends CrudRepository<Post, UUID> {
@OrderBy("createdAt")
List<Post> byStatus(Status status);

@Query("delete from Post")
@Delete
@Transactional
long deleteAll();
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.example.demo;

import com.example.demo.model.Post;
import com.example.demo.model.PostSummary;
import com.example.demo.model.Status;
import com.example.demo.repository.PostRepository;
import lombok.SneakyThrows;
Expand All @@ -17,6 +18,7 @@
import org.springframework.core.env.MapPropertySource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.transaction.support.TransactionTemplate;
import org.testcontainers.containers.PostgreSQLContainer;

import java.util.List;
Expand All @@ -28,7 +30,7 @@
* @author hantsy
*/
@Slf4j
@SpringJUnitConfig(classes = {DataSourceConfig.class, HibernateConfig.class, DataConfig.class,
@SpringJUnitConfig(classes = {DataSourceConfig.class, JpaConfig.class, DataConfig.class,
PostRepositoryTest.TestConfig.class})
@ContextConfiguration(initializers = PostRepositoryTest.TestContainerInitializer.class)
public class PostRepositoryTest {
Expand Down Expand Up @@ -59,12 +61,21 @@ public void initialize(ConfigurableApplicationContext configurableApplicationCon
@Autowired
PostRepository posts;

@Autowired
Blogger blogger;

@Autowired
TransactionTemplate txTemplate;

@SneakyThrows
@BeforeEach
public void setup() {
this.posts.findAll().forEach(this.posts::delete);
// var deleted = posts.deleteAll();
// log.debug("deleted posts: {}", deleted);

// txTemplate.executeWithoutResult(transactionStatus -> {
// var deleted = posts.deleteAll();
// log.debug("deleted posts: {}", deleted);
// });
}

@Test
Expand All @@ -90,8 +101,21 @@ public void testInsertAndQuery() {
assertThat(saved.getStatus()).isEqualTo(Status.DRAFT);
}

@Test
public void testBlogger() {
var data = Post.builder().title("test").content("test content").status(Status.DRAFT).build();
var saved = blogger.newPost(data);
assertThat(this.posts.findById(saved.getId()).isPresent()).isTrue();

saved.setStatus(Status.PUBLISHED);
posts.update(saved);

List<PostSummary> allPublished = blogger.allPublishedPosts();
assertThat(allPublished.size()).isEqualTo(1);
}

@Configuration
@ComponentScan(basePackageClasses = HibernateConfig.class)
@ComponentScan(basePackageClasses = JpaConfig.class)
static class TestConfig {
}

Expand Down

0 comments on commit 221be33

Please sign in to comment.