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

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...

Related

AspectJ (Spring) + how to add the embedding of an aspect in a private method and get the specified data

I have created an aspect that should embed logging on methods marked with an annotation and with the private modifier.
In addition, I would like to add information to the log that will be available at the time of execution of the method (for example, the object with which the method works and the name of the method and the class with which it is currently working).
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
...
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.3.9</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
UserController
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
#GetMapping
public List<User> getUsers() {
List<User> userList = getUsersInternal();
return userList;
}
#AuditAnnotation()
private List<User> getUsersInternal() {
List<User> allUsers = userService.getAllUsers();
return allUsers;
}
}
annotation
#Retention(RUNTIME)
#Target(METHOD)
#Documented
public #interface AuditAnnotation {
public String nameMethod() default "";
}
loggingService
public interface LoggingService {
void log(String message);
}
/**
* A dummy implementation of logging service,
* just to inject it in {#link com.aspectj.in.spring.boot.aop.aspect.auditlog.interceptor.LoggingInterceptorAspect}
* that's managed by AspectJ
*/
#Service
public class DefaultLoggingService implements LoggingService {
private static final Logger logger = LoggerFactory.getLogger("sample-spring-aspectj");
#Override
public void log(String message) {
logger.info(message);
}
}
aspect
#Aspect
#Component
public class LoggingInterceptorAspect {
#Autowired
private LoggingService loggingService;
#Pointcut("execution(private * *(..))")
public void privateMethod() {}
#Pointcut("#annotation(com.aspectj.in.spring.boot.aop.aspect.auditlog.annotation.AuditAnnotation)")
public void annotatedMethodCustom() {}
#Before("annotatedMethodCustom() && privateMethod()")
public void addCommandDetailsToMessage() throws Throwable {
ZonedDateTime dateTime = ZonedDateTime.now(ZoneOffset.UTC);
String message = String.format("User controller getUsers method called at %s", dateTime);
System.out.println("+++++++++++++++++++++++++");
loggingService.log(message);
}
}
configuratinAspect
#Configuration
public class LoggingInterceptorConfig {
#Bean
public LoggingInterceptorAspect getAutowireCapableLoggingInterceptor() {
return Aspects.aspectOf(LoggingInterceptorAspect.class);
}
}
test
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class AspectjInSpringBootApplicationTests {
#Autowired
protected TestRestTemplate testRestTemplate;
}
class UserControllerTest extends AspectjInSpringBootApplicationTests {
#Test
void getUsers() {
String url = "/v1/users";
ParameterizedTypeReference<List<User>> typeReference =
new ParameterizedTypeReference<>() {
};
ResponseEntity<List<User>> responseEntity =
testRestTemplate.exchange(url, HttpMethod.GET, null, typeReference);
HttpStatus statusCode = responseEntity.getStatusCode();
assertThat(statusCode, is(HttpStatus.OK));
List<User> employeeDtoList = responseEntity.getBody();
System.out.println(employeeDtoList);
}
}
But at the moment I have no errors .
so far, I see that the aspect is embedded,
but I want it to be detailed so that the aspect is universal and I would not have to explicitly specify in the message in which class it works.
Maybe someone has ideas on how to fix it.
I suggest you to explore the AspectJ documentation and the JoinPoint API, too. Here is a little example in stand-alone AspectJ without Spring. You can adjust it to your needs:
package de.scrum_master.app;
public class Application {
public static void main(String[] args) {
Application application = new Application();
System.out.println(application.add(4, application.multiply(2, 3)));
application.divide(5, 0);
}
private int add(int i, int j) {
return i + j;
}
private int multiply(int i, int j) {
return i * j;
}
private double divide(int i, int j) {
return i / j;
}
}
package de.scrum_master.aspect;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
#Aspect
public class MyAspect {
#Before("execution(private * *(..))")
public void beforeAdvice(JoinPoint joinPoint) {
System.out.println(joinPoint);
System.out.println(" Signature: " + joinPoint.getSignature());
System.out.println(" Target: " + joinPoint.getTarget());
System.out.println(" Arguments: " + Arrays.deepToString(joinPoint.getArgs()));
}
#AfterReturning(pointcut = "execution(private * *(..))", returning = "result")
public void afterReturningAdvice(JoinPoint joinPoint, Object result) {
System.out.println(" Result: " + result);
}
#AfterThrowing(pointcut = "execution(private * *(..))", throwing = "exception")
public void afterThrowingAdvice(JoinPoint joinPoint, Throwable exception) {
System.out.println(" Exception: " + exception);
}
}
Console log:
Picked up _JAVA_OPTIONS: -Djava.net.preferIPv4Stack=true
execution(int de.scrum_master.app.Application.multiply(int, int))
Signature: int de.scrum_master.app.Application.multiply(int, int)
Target: de.scrum_master.app.Application#7cdbc5d3
Arguments: [2, 3]
Result: 6
execution(int de.scrum_master.app.Application.add(int, int))
Signature: int de.scrum_master.app.Application.add(int, int)
Target: de.scrum_master.app.Application#7cdbc5d3
Arguments: [4, 6]
Result: 10
10
execution(double de.scrum_master.app.Application.divide(int, int))
Signature: double de.scrum_master.app.Application.divide(int, int)
Target: de.scrum_master.app.Application#7cdbc5d3
Arguments: [5, 0]
Exception: java.lang.ArithmeticException: / by zero
Exception in thread "main" java.lang.ArithmeticException: / by zero
at de.scrum_master.app.Application.divide(Application.java:19)
at de.scrum_master.app.Application.main(Application.java:7)
In addition to the context data I printed here, you can also get annotations and their properties, method parameter names (even though I think that is unnecessary and availability depends on compilation options) etc.

Error creating Bean with name EntityManagerFactory

Hello every body i'm developping an authentication service using spring security & mysql database and ia have this error when running my springboot app
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]
Here is my pom.xml
<dependencies>
<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.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.7.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
and this is my SecurityConfig.java
#EnableGlobalMethodSecurity(prePostEnabled = true)
#EnableWebSecurity
#EnableJpaRepositories(basePackageClasses = UsersRepository.class)
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private MyUserDetailsService myUserDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailsService)
.passwordEncoder(getPasswordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers("**/admin/**").authenticated()
.anyRequest().permitAll()
.and()
.formLogin().permitAll();
}
private PasswordEncoder getPasswordEncoder() {
return new PasswordEncoder() {
#Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
#Override
public boolean matches(CharSequence charSequence, String s) {
return true;
}
};
}
}
this is my Users.java
#Entity
#Table(name = "user")
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id")
private int id;
#Column(name = "login")
private String login;
#Column(name = "password")
private String password;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "user_role", joinColumns = #JoinColumn(name = "user_id"), inverseJoinColumns = #JoinColumn(name = "role_id"))
private Set<Role> roles;
public Users() {
}
public Users(Users users){
this.id=users.getId();
this.login=users.getLogin();
this.password=users.getPassword();
this.roles=users.getRoles();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
this is the roles.java
#Entity
#Table(name = "role")
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "role_id")
private int roleId;
#Column(name = "role")
private String role;
public Role() {
}
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
this is my UsersRepository.java
#Repository
public interface UsersRepository extends JpaRepository<Users, Integer> {
Optional<Users> findByName(String username);
}
this is MyUserDetailsService.java
#Service
public class MyUserDetailsService implements UserDetailsService {
#Autowired
private UsersRepository usersRepository;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<Users> optionalUsers = usersRepository.findByName(username);
optionalUsers
.orElseThrow(() -> new UsernameNotFoundException("Utilisateur Introuvable!"));
return optionalUsers
.map(MyUserDetails::new).get();
}
}
this is MyUserDetails.java
public class MyUserDetails extends Users implements UserDetails {
public MyUserDetails(final Users users) {
super(users);
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles()
.stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role.getRole()))
.collect(Collectors.toList());
}
#Override
public String getPassword() {
return super.getPassword();
}
#Override
public String getUsername() {
return super.getLogin();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
and finally my controller of ressources AuthenticationCOntroller.java
#RequestMapping("/api")
#RestController
public class AuthentificationController {
#GetMapping(value = "/login")
public String hello() {
return "Hello World";
}
#PreAuthorize("hasAnyRole('ADMIN')")
#GetMapping("/admin/login")
public String helloAdmin() {
return "Hello ADMIN";
}
#GetMapping("/login/alternate")
public String alternate() {
return "alternate";
}
}
this is application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password =
spring.datasource.testWhileIdle=true
spring.datasource.validationQuery=SELECT 1
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
I'm using and MYSQL database it is well connected and the tables are created with some values.
Thank you and waiting for you answers.
if you are using java version 9+, add following too and remove hibernate core dependency as its already included in spring boot jpa starter.
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
Remove the Hibernate dependency because spring-boot-starter-data-jpa already has it.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.7.Final</version>
</dependency>
Hope this works :)
There is a conflict in pom.xml dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
spring-boot-starter-jpa has hibernate-core dependency included.
It is possible to view the dependency graph of a project like so:
mvn dependency:tree
mvn dependency:list
These commands will show what version of Hibernate included in the compilation.
To fix the UnsatisfiedDependencyException of entityManagerFactory bean, simply delete hibernate-core dependency from the pom.xml
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.7.Final</version>
</dependency>

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 REST Controller Not Starting

pom.xml
<groupId>com.ibm.springboot</groupId>
<artifactId>spring-boot-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-api</name>
<description>Spring API DATA</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.14.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
SpringBootApiApplication.java
#SpringBootApplication
#ComponentScan("com.ibm.springboot.*")
#EntityScan("com.ibm.springboot.topics.Topic")
#EnableJpaRepositories("com.ibm.springboot.topics.TopicRepository")
public class SpringBootApiApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootApiApplication.class, args);
}
}
Topic.java
#Entity
public class Topic {
#Id
private String id;
private String name;
private String description;
public Topic(String id, String name, String description) {
super();
this.id = id;
this.name = name;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
TopicController.java
#RestController
public class TopicController {
#Autowired
TopicService topicService;
#RequestMapping("/topics")
public List<Topic> getAllTopics(){
return topicService.getAllTopics();
}
#RequestMapping(method=RequestMethod.POST,value="/topics")
public void addTopic(#RequestBody Topic topic){
topicService.addTopic(topic);
}
}
TopicRepository.java
#Repository
public interface TopicRepository extends CrudRepository<Topic, String>{
}
TopicService.java
#Service
public class TopicService {
#Autowired
TopicRepository topicRepository;
public List<Topic> getAllTopics(){
List<Topic> topics = new ArrayList<>();
topicRepository.findAll().forEach(topics::add);
return topics;
}
public void addTopic(Topic topic){
// topics.add(topic);
topicRepository.save(topic);
}
}
While I am running the main class , I am getting the following error.
APPLICATION FAILED TO START
Description:
Field topicRepository in com.ibm.springboot.topics.TopicService
required a bean of type 'com.ibm.springboot.topics.TopicRepository'
that could not be found.
Action:
Consider defining a bean of type 'com.ibm.springboot.topics.TopicRepository' in your configuration.
I have checked all the related suggestion given here, but nothing clicked.Please help
Remove the #Repository annotation from your TopicRepository interface.
Should be (no annotation over it):
public interface TopicRepository extends CrudRepository{
}
EDIT
Change your:
#EnableJpaRepositories("com.ibm.springboot.topics.TopicRepository")
To:
#EnableJpaRepositories(basePackageClasses= {com.ibm.springboot.topics.TopicRepository.class})

Spring boot - configure EntityManager

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

Resources