Spring boot - configure EntityManager - spring-boot

I was using Google guice in my project and now I tried to convert the framework to SpringBoot totally.
I configured the Bean for persistence.xml like below in
#Autowired
#Bean(name = "transactionManager")
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
{
LocalContainerEntityManagerFactoryBean lEMF = new LocalContainerEntityManagerFactoryBean();
lEMF.setPersistenceUnitName("leaseManagementPU");
lEMF.setPersistenceXmlLocation("persistence.xml");
return lEMF;
}
Now I need to configure(Inject) EntityManager em, to do JPA operations like em.persist(), em.find etc... How do I configure, also someone try to explain this with sample code

With Spring Boot its not necessary to have any config file like persistence.xml. You can configure with annotations Just configure your DB config for JPA in the
application.properties
spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:#DB...
spring.datasource.username=username
spring.datasource.password=pass
spring.jpa.database-platform=org.hibernate.dialect....
spring.jpa.show-sql=true
Then you can use CrudRepository provided by Spring where you have standard CRUD transaction methods. There you can also implement your own SQL's like JPQL.
#Transactional
public interface ObjectRepository extends CrudRepository<Object, Long> {
...
}
And if you still need to use the Entity Manager you can create another class.
public class ObjectRepositoryImpl implements ObjectCustomMethods{
#PersistenceContext
private EntityManager em;
}
This should be in your pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
</dependencies>

Hmmm you can find lot of examples for configuring spring framework. Anyways here is a sample
#Configuration
#Import({PersistenceConfig.class})
#ComponentScan(basePackageClasses = {
ServiceMarker.class,
RepositoryMarker.class }
)
public class AppConfig {
}
PersistenceConfig
#Configuration
#PropertySource(value = { "classpath:database/jdbc.properties" })
#EnableTransactionManagement
public class PersistenceConfig {
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH = "hibernate.max_fetch_depth";
private static final String PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE = "hibernate.jdbc.fetch_size";
private static final String PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE = "hibernate.jdbc.batch_size";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String[] ENTITYMANAGER_PACKAGES_TO_SCAN = {"a.b.c.entities", "a.b.c.converters"};
#Autowired
private Environment env;
#Bean(destroyMethod = "close")
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
return dataSource;
}
#Bean
public JpaTransactionManager jpaTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
return transactionManager;
}
private HibernateJpaVendorAdapter vendorAdaptor() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setShowSql(true);
return vendorAdapter;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdaptor());
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
entityManagerFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
entityManagerFactoryBean.setJpaProperties(jpaHibernateProperties());
return entityManagerFactoryBean;
}
private Properties jpaHibernateProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH, env.getProperty(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH));
properties.put(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE));
properties.put(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
properties.put(AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, "none");
properties.put(AvailableSettings.USE_CLASS_ENHANCER, "false");
return properties;
}
}
Main
public static void main(String[] args) {
try (GenericApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)) {
MyService myService = springContext.getBean(MyServiceImpl.class);
try {
myService.handleProcess(fromDate, toDate);
} catch (Exception e) {
logger.error("Exception occurs", e);
myService.handleException(fromDate, toDate, e);
}
} catch (Exception e) {
logger.error("Exception occurs in loading Spring context: ", e);
}
}
MyService
#Service
public class MyServiceImpl implements MyService {
#Inject
private MyDao myDao;
#Override
public void handleProcess(String fromDate, String toDate) {
List<Student> myList = myDao.select(fromDate, toDate);
}
}
MyDaoImpl
#Repository
#Transactional
public class MyDaoImpl implements MyDao {
#PersistenceContext
private EntityManager entityManager;
public Student select(String fromDate, String toDate){
TypedQuery<Student> query = entityManager.createNamedQuery("Student.findByKey", Student.class);
query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);
List<Student> list = query.getResultList();
return CollectionUtils.isEmpty(list) ? null : list;
}
}
Assuming maven project:
Properties file should be in src/main/resources/database folder
jdbc.properties file
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=your db url
jdbc.username=your Username
jdbc.password=Your password
hibernate.max_fetch_depth = 3
hibernate.jdbc.fetch_size = 50
hibernate.jdbc.batch_size = 10
hibernate.show_sql = true
ServiceMarker and RepositoryMarker are just empty interfaces in your service or repository impl package.
Let's say you have package name a.b.c.service.impl. MyServiceImpl is in this package and so is ServiceMarker.
public interface ServiceMarker {
}
Same for repository marker. Let's say you have a.b.c.repository.impl or a.b.c.dao.impl package name. Then MyDaoImpl is in this this package and also Repositorymarker
public interface RepositoryMarker {
}
a.b.c.entities.Student
//dummy class and dummy query
#Entity
#NamedQueries({
#NamedQuery(name="Student.findByKey", query="select s from Student s where s.fromDate=:fromDate" and s.toDate = :toDate)
})
public class Student implements Serializable {
private LocalDateTime fromDate;
private LocalDateTime toDate;
//getters setters
}
a.b.c.converters
#Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
#Override
public Timestamp convertToDatabaseColumn(LocalDateTime dateTime) {
if (dateTime == null) {
return null;
}
return Timestamp.valueOf(dateTime);
}
#Override
public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {
if (timestamp == null) {
return null;
}
return timestamp.toLocalDateTime();
}
}
pom.xml
<properties>
<java-version>1.8</java-version>
<org.springframework-version>4.2.1.RELEASE</org.springframework-version>
<hibernate-entitymanager.version>5.0.2.Final</hibernate-entitymanager.version>
<commons-dbcp2.version>2.1.1</commons-dbcp2.version>
<mysql-connector-java.version>5.1.36</mysql-connector-java.version>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate-entitymanager.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${commons-dbcp2.version}</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
</plugins>
</build>
Hope it helps. Thanks

Related

Feign Client with Spring Cloud GatewayFilter cause cycle dependency

During certain checks, I need to make a request to my Microservice in the Gateway Filter.
When I define the Feign class in the GatewayFilter(my SecurityFilter.java) class, it gives the following error.
How can I resolve this situation.
Error:
Description:
The dependencies of some of the beans in the application context form a cycle:
┌─────┐
| securityFilter defined in file [/target/classes/com/example/SecurityFilter.class]
↑ ↓
| cachedCompositeRouteLocator defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]
↑ ↓
| routeDefinitionRouteLocator defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]
└─────┘
Action:
Despite circular references being allowed, the dependency cycle between beans could not be broken. Update your application to remove the dependency cycle.
GatewayFilter class
#Component
public class SecurityFilter implements GatewayFilterFactory<SecurityFilter.Config> {
private final UserApi userApi;
public SecurityFilter(UserApi userApi) {
this.userApi = userApi;
}
#Override
public GatewayFilter apply(Config config) {
return ((exchange, chain) -> {
return chain.filter(exchange.mutate().request(exchange.getRequest()).build());
});
}
#Override
public Class<Config> getConfigClass() {
return Config.class;
}
#Override
public Config newConfig() {
Config c = new Config();
return c;
}
public static class Config {
}
}
pom.xml
<properties>
<java.version>17</java.version>
<spring-cloud.version>2021.0.3</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Main class
#SpringBootApplication
#ComponentScan("com.example")
#EnableFeignClients(basePackages = {"com.example.feign"})
public class GatewayApplicationMain {
public static void main(String[] args) {
SpringApplication.run(GatewayApplicationMain.class, args);
}
}
Feign api class
#FeignClient(name = "user", path="userService/", url="http://localhost:8091/")
public interface UserApi {
#GetMapping("/getUserByUserName/{userName}")
ResponseEntity<Object> getUserByUserName(#PathVariable(name = "userName") String userName);
}
Security class
#Configuration
public class SecurityConfig {
#Bean
public SecurityWebFilterChain configure(ServerHttpSecurity http) {
http.csrf().disable()
.authorizeExchange()
.anyExchange()
.authenticated()
.and()
.oauth2Login()
.and().oauth2ResourceServer().jwt();
return http.build();
}
}
application.properties file
server.port=8090
spring.main.allow-circular-references=true
private final UserApi userApi;
#Autowired
public SecurityFilter(#Lazy UserApi userApi) {
this.userApi = userApi;
}
This is how I was able to fix the problem by adding #Lazy.
If you intend to keep the circular dependency you can add this configuration
spring.main.allow-circular-references: true
I'm using #Lazy annotation whenever the feign client intent to be use, to avoid Circular Reference Error when using spring-cloud-gateway along with OpenFeign, even in my CustomGatewayFilter :)
#Component
public class CustomApiGatewayFilter extends AbstractGatewayFilterFactory<CustomApiGatewayFilter.Config> {
private static Logger logger = LogManager.getLogger(CustomApiGatewayFilter.class);
private final JwtConfig jwtConfig;
private final ThirdPartyFeignClientService thirdPartyFeignClientService;
public CustomApiGatewayFilter(JwtConfig jwtConfig, #Lazy ThirdPartyFeignClientService thirdPartyFeignClientService) {
super(Config.class);
this.jwtConfig = jwtConfig;
this.thirdPartyFeignClientService = thirdPartyFeignClientService;
}
....
....
}
And the usage of this feign client placed on a separate function used by this filter
private String validateToken(String jwtToken) throws MyAppException {
String json = "";
ObjectMapper mapper = new ObjectMapper();
try {
Claims claims = jwtConfig.getAllClaimsFromToken(jwtToken);
String additionalInfo = (String) claims.get("additionalInfo");
JwtPayload payload = mapper.readValue(additionalInfo, JwtPayload.class);
String username = jwtConfig.getUsernameFromToken(jwtToken);
if(thirdPartyFeignClientService.validateClient(payload.getClientId(), payload.getClientSecret())){
return username;
}else{
throw new MyAppException("Invalid Client", ErrorCode.GENERIC_FAILURE);
}
} catch (ExpiredJwtException e) {
logger.error(e.getMessage());
throw new MyAppException(e.getMessage(), ErrorCode.GENERIC_FAILURE);
} catch (Exception e) {
logger.error("Other Exception :" + e);
throw new MyAppException (e.getMessage(), ErrorCode.GENERIC_FAILURE);
}
}
And it works :)

Error creating bean with name 'activityController'

I'm having this problem while running on Server (Tomcat) my project. I have created a Maven project using Spring. The Java version is Java 1.8.
NO SPRING-BOOT!
Error creating bean with name 'activityController': Unsatisfied dependency expressed through field 'activityService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'activityService': Unsatisfied dependency expressed through field 'dao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.calendar.repository.ActivityDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Could you please help me? Thank you!
This is the code.
Thank you!!!
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.calendar</groupId>
<artifactId>calendar</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Calendar</name>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springframework.version>5.1.4.RELEASE</springframework.version>
<jackson.version>2.11.2</jackson.version>
<email.version>1.6.2</email.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.4.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.0</version>
</dependency>
</dependencies>
<repositories>
</repositories>
<build>
<finalName>company-calendar</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Activity.java
package com.calendar.entity;
import java.io.Serializable;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.List;
/**
* The persistent class for the activity database table.
*
*/
#Entity
#NamedQuery(name = "Activity.findAll", query = "SELECT a FROM Activity a")
public class Activity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Integer id;
#Column(name = "create_time")
private Timestamp createTime;
#Column(name = "created_by")
private String createdBy;
private String description;
#Column(name = "update_time")
private Timestamp updateTime;
#Column(name = "updated_by")
private String updatedBy;
//bi-directional many-to-one association to CalendarHeader
#OneToMany(mappedBy = "activity")
private List<CalendarHeader> calendarHeaders;
public Activity() {
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Timestamp getCreateTime() {
return this.createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
public String getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public Timestamp getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(Timestamp updateTime) {
this.updateTime = updateTime;
}
public String getUpdatedBy() {
return this.updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
public List<CalendarHeader> getCalendarHeaders() {
return this.calendarHeaders;
}
public void setCalendarHeaders(List<CalendarHeader> calendarHeaders) {
this.calendarHeaders = calendarHeaders;
}
public CalendarHeader addCalendarHeader(CalendarHeader calendarHeader) {
getCalendarHeaders().add(calendarHeader);
calendarHeader.setActivity(this);
return calendarHeader;
}
public CalendarHeader removeCalendarHeader(CalendarHeader calendarHeader) {
getCalendarHeaders().remove(calendarHeader);
calendarHeader.setActivity(null);
return calendarHeader;
}
}
ActivityDAO.java
package com.calendar.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.calendar.entity.Activity;
#Repository
public interface ActivityDAO extends JpaRepository<Activity, Integer> {}
**ActivityDTO.java**
package com.calendar.dto;
import java.sql.Timestamp;
public class ActivityDTO {
private Integer id;
private String description;
private Timestamp createTime;
private String createdBy;
private Timestamp updateTime;
private String updatedBy;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Timestamp getCreateTime() {
return createTime;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Timestamp getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Timestamp updateTime) {
this.updateTime = updateTime;
}
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
}
ActivityService.java
package com.calendar.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.calendar.dto.ActivityDTO;
import com.calendar.repository.ActivityDAO;
import com.calendar.entity.Activity;
#Service
public class ActivityService {
#Autowired
ActivityDAO dao;
public List<ActivityDTO> findAll() {
List<ActivityDTO> DTOList = new ArrayList<ActivityDTO>();
List<Activity> entity = dao.findAll();
if (entity != null) {
for (Activity e : entity) {
DTOList.add(getDTOFromEntity(e));
}
}
return DTOList;
};
protected ActivityDTO getDTOFromEntity(Activity entity) {
ActivityDTO activityDTO = new ActivityDTO();
activityDTO.setId(entity.getId());
activityDTO.setDescription(entity.getDescription());
activityDTO.setCreatedBy(entity.getCreatedBy());
activityDTO.setCreateTime(entity.getCreateTime());
activityDTO.setUpdatedBy(entity.getUpdatedBy());
activityDTO.setUpdateTime(entity.getUpdateTime());
return activityDTO;
}
}
ActivityController.java
package com.calendar.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.calendar.dto.ActivityDTO;
import com.calendar.service.ActivityService;
#RestController
#RequestMapping("activity")
public class ActivityController {
#Autowired
private ActivityService activityService;
private ActivityService getService() {
System.out.println("service= " + activityService);
return activityService;
}
#Transactional(readOnly = true)
#GetMapping("")
#ResponseBody
public List<ActivityDTO> findAll() {
System.out.println("SIL findAll");
return getService().findAll();
}
}
AppConfig.java
package com.calendar.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.LocalEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan(basePackages = "com.calendar")
public class AppConfig implements WebMvcConfigurer {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
//to see html files
configurer.enable();
}
//Entity manager
#Bean(name = "Calendar_PU")
public LocalEntityManagerFactoryBean getEntityManagerFactoryBean() {
LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
factoryBean.setPersistenceUnitName("Calendar_PU");
return factoryBean;
}
}
Regards,
Francesco
Try adding #EnableJpaRepositories to your AppConfig:
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = "com.calendar.repository")
#ComponentScan(basePackages = "com.calendar")
public class AppConfig implements WebMvcConfigurer {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
//to see html files
configurer.enable();
}
//Entity manager
#Bean(name = "Calendar_PU")
public LocalEntityManagerFactoryBean getEntityManagerFactoryBean() {
LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
factoryBean.setPersistenceUnitName("Calendar_PU");
return factoryBean;
}
}
You also need to change your pom.xml. There are too many dependencies (most of them are already part of spring-data-jpa) and spring-data-jpa requires Spring 5.3.5.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.calendar</groupId>
<artifactId>calendar</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Calendar</name>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springframework.version>5.3.5</springframework.version>
<jackson.version>2.11.2</jackson.version>
<email.version>1.6.2</email.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.4.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.0</version>
</dependency>
</dependencies>
<repositories>
</repositories>
<build>
<finalName>company-calendar</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
This is why you should consider using Spring Boot. You will avoid issues with dependencies that do not work together.

JavaFX 12 maven and Spring

I'm trying to add spring to my pom
but I'm wondering if my build will look like this.
Could someone help me how can I do this spring integration with java fx?
my pom:
<properties>
<java.version>12</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>12.0.2</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>12.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
main class:
public class App extends Application {
private static Scene scene;
#Override
public void start(Stage stage) throws IOException {
scene = new Scene(loadFXML("primary"));
stage.setScene(scene);
stage.show();
}
static void setRoot(String fxml) throws IOException {
scene.setRoot(loadFXML(fxml));
}
private static Parent loadFXML(String fxml) throws IOException {
FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(fxml + ".fxml"));
return fxmlLoader.load();
}
public static void main(String[] args) {
launch();
} }
I searched and found nothing about integrating javafx with spring
Could someone help me how I can integrate spring?
I tried to use what I used in my swing project but it didn't work out
Your main app has to maintain Spring's application context like this.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
#Configuration // or #SpringBootApplication if you used spring boot.
public class App extends Application {
private static Scene scene;
private AbstractApplicationContext context;
#Override
public void init() throws Exception {
this.context = new AnnotationConfigApplicationContext(App.class);
super.init();
}
#Override
public void start(Stage stage) throws IOException {
SpringFxmlLoader loader = new SpringFxmlLoader(this.context);
Parent root = loader.loadFromResource("primary.fxml");
stage.setScene(new Scene(root));
stage.show();
}
public static void main(String[] args) {
launch();
}
}
use SpringFxmlLoader for returning a controller as a spring bean.
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.springframework.context.ApplicationContext;
import javafx.fxml.FXMLLoader;
public class SpringFxmlLoader extends FXMLLoader {
private ApplicationContext context;
protected SpringFxmlLoader() {
}
public SpringFxmlLoader(ApplicationContext context) {
this.context = context;
setControllerFactory(context::getBean); // return a spring bean from spring's application context.
}
public ApplicationContext getContext() {
return this.context;
}
public <T> T loadFromResource(String resource) throws IOException {
return loadFromResource(resource, null);
}
public <T> T loadFromResource(String resource, Class<?> root) throws IOException {
URL resourceURL = context.getResource(resource).getURL();
setLocation(resourceURL);
if(root != null) setRoot(root);
try (InputStream fxml = resourceURL.openStream()) {
return load(fxml);
}
}
}
Your controller should be looked like this as a spring bean.
#Controller
#Scope("prototype")
public class PrimaryController {
#FXML private Parent rootView;
#FXML private TitledPane settingPane;
#Autowired private SomeBean someBean; // now you can autowire spring beans.
// braa....
}
Don't forget specify the controller class in your primary.fxml with fx:controller attribute.

spring-boot-starter-data-jpa insert query does not save the data in database

I am using spring-boot-starter-data-jpa. While trying to insert the data in database, the utility executes without any error but the data is not persisted in the database.
I can also see the insert query on the console
I am not sure what exactly is going wrong here.
POM.XML
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- Spring data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
</dependencies>
Main class
#SpringBootApplication
public class Application implements CommandLineRunner {
#Autowired
DataSource dataSource;
#Autowired
ElementDetailsRepository elementDetailsDAO;
#Autowired
ElementDetailsEntity elementDetailsEntity;
#Autowired
ElementDetailsPK elementDetailsPK;
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
#Transactional(propagation = Propagation.NESTED)
#Override
public void run(String... args) throws Exception {
for (ExcelPojo excelPojo : listOfExcelElements) {
if (excelPojo.getRecordType().equalsIgnoreCase("Item")) {
if (excelPojo.getMarket().equalsIgnoreCase("UK")) {
Integer elementID = elementDetailsDAO.findDNAElementId(excelPojo.getMarket(), 992,
excelPojo.getGenesisID(), "EN");
System.out.println("UK ITEM..." + elementID);
int flag = elementDetailsDAO.createPIMIDAttributeValue(excelPojo.getMarket(), 1914, excelPojo.getPimID(),elementID, "EN", getCurrentTime(), getUser());
}
}
Repository
#Repository
public interface ElementDetailsRepository extends JpaRepository<ElementDetailsEntity,Integer> {
#Query(value = QueryConstants.findElementId, nativeQuery = true)
public Integer findDNAElementId(#Param("country_code") String country_code, #Param("config_id") int config_id,
#Param("import_id") String import_id,#Param("language_code")String language_code);
#Modifying
#Query(value = QueryConstants.createPIMIDAttributeValue, nativeQuery = true)
public int createPIMIDAttributeValue(#Param("countrycode") String countrycode, #Param("configid") int configid,
#Param("pimid") String attribute_value, #Param("elementid") int elementId,#Param ("languageCode") String language_code,#Param("date") String date,#Param("user") String user);
}
Entity
#Service
#Entity
#Table(name = "element_details")
public class ElementDetailsEntity extends BaseDataObject {
private static final long serialVersionUID = -8033261173844397824L;
#EmbeddedId
private ElementDetailsPK elementDetailsPK;
#Column(name = "status_id")
private Integer statusId;
#Column(name = "attribute_value")
private String attributeValue;
#Column(name = "is_dirty")
private Boolean isDirty;
}
Application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/wxb_prod
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto = none
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
logging.level.org.hibernate.SQL=TRACE
spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5
Try using annotation #EnableJpaRepositories in your main class

Spring annotation gives null value in my Spring MVC when I create JAX-RS Web service

I added JAX-RS Web service for my project .I want to get XML file. It works fine when I hard cord something on return statement and it works fine. But I want to get data from my database. I use
#Autowired
private ProductServices productServices;
for call Spring Service class... For other normal controllers this #Autowired working fine. In JAX-RS it doesn't works.
JAX-RS gives null value like this
I want to call this service for get data to my method. How can I do that..
This is my Model.
#Entity
#Table(name = "products")
#XmlRootElement
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "product_id")
private long productId;
#NotNull
private String serialNo;
#NotNull
private int slsiUnit;
#NotNull
private String itemDesc;
#NotNull
private int slsNo;
#NotNull
private String hsCode;
#NotNull
private String userIDandTime;
#NotNull
private String recentUpdateBy;
public long getProductId() {
return productId;
}
public void setProductId(long productId) {
this.productId = productId;
}
public String getSerialNo() {
return serialNo;
}
public void setSerialNo(String serialNo) {
this.serialNo = serialNo;
}
public int getSlsiUnit() {
return slsiUnit;
}
public void setSlsiUnit(int slsiUnit) {
this.slsiUnit = slsiUnit;
}
public String getItemDesc() {
return itemDesc;
}
public void setItemDesc(String itemDesc) {
this.itemDesc = itemDesc;
}
public int getSlsNo() {
return slsNo;
}
public void setSlsNo(int slsNo) {
this.slsNo = slsNo;
}
public String getHsCode() {
return hsCode;
}
public void setHsCode(String hsCode) {
this.hsCode = hsCode;
}
public String getUserIDandTime() {
return userIDandTime;
}
public void setUserIDandTime(String userIDandTime) {
this.userIDandTime = userIDandTime;
}
public String getRecentUpdateBy() {
return recentUpdateBy;
}
public void setRecentUpdateBy(String recentUpdateBy) {
this.recentUpdateBy = recentUpdateBy;
}
}
This is my Repository.
public interface ProductRepository extends CrudRepository<Product, Long> {
#Override
Product save(Product product);
#Override
Product findOne(Long productId);
#Override
List<Product> findAll();
#Override
void delete(Long productId);
}
This is my Services class
#Service
public class ProductServices {
private static final Logger serviceLogger = LogManager.getLogger(ProductServices.class);
#Autowired
private ProductRepository productRepository;
public List<Product> getProductList() {
return productRepository.findAll();
}
public Product getProductById(long productId) {
return productRepository.findOne(productId);
}
}
This is my JAX-RS Web Service class
#Path("release")
public class GenericResource {
#Context
private UriInfo context;
#Autowired
private ProductServices productServices;
public GenericResource() {
}
#GET
#Produces(MediaType.APPLICATION_XML)
public List<Product> getXml() {
List<Product> a = productServices.getProductList();
return a;
}
}
This is the MessageBodyWriter
#Provider
#Produces(MediaType.APPLICATION_XML)
public class restConverter implements MessageBodyWriter<List<Product>> {
#Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return Product.class.isAssignableFrom(type);
}
#Override
public long getSize(List<Product> t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return -1;
}
#Override
public void writeTo(List<Product> t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
out.write(t.toString().getBytes());
}
}
This is a extend class for JSX-RS
#ApplicationPath("TransferPermit/Slsi_Customs/restAPI")
public class restConfig extends Application{
}
This is my pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<!--handle servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!--<Email Dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>1.4.3.RELEASE</version>
</dependency>
<!--Add mysql dependency-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<!--jasper-->
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>3.7.6</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.bundles</groupId>
<artifactId>jaxrs-ri</artifactId>
<version>2.13</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.5</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
<type>jar</type>
</dependency>
</dependencies>
Special : This cord works fine. But in Web service class productServices auto-wired dependency not working. What is the error :
#RequestMapping(value = "/ViewProduct", produces = {MediaType.APPLICATION_JSON_VALUE}, method = RequestMethod.GET)
#JsonIgnore
public ResponseEntity<List<Product>> listAllProducts() {
List<Product> viewProducts = productServices.getProductList();
if (viewProducts.isEmpty()) {
return new ResponseEntity<List<Product>>(HttpStatus.NO_CONTENT);
}
System.out.println("entity " + new ResponseEntity<List<Product>>(HttpStatus.NO_CONTENT));
return new ResponseEntity<List<Product>>(viewProducts, HttpStatus.OK);
}
What is the error in my cord. How can I call data from database
Please help me someone for return XML...

Resources