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

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

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

H2 Schema Empty in Spring Boot Application

I'm setting up a barebones Spring Boot project described here and I'm running into issues with the basic setup.
It seems that the DatabaseLoader does not get invoked, and when I open the H2 Console for this project I see no schema containing an Employee table.
Here's the relevant part of 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-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<!--
<scope>runtime</scope>
-->
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
my domain:
#Data
#Entity
public class Employee {
private #Id #GeneratedValue Long id;
private String firstName;
private String lastName;
private String description;
public Employee() {}
public Employee(String firstName, String lastName, String description) {
this.firstName = firstName;
this.lastName = lastName;
this.description = description;
}
}
And the database loader:
public class DatabaseLoader implements CommandLineRunner {
private final EmployeeRepository repository;
#Autowired
public DatabaseLoader(EmployeeRepository repository) {
this.repository = repository;
}
#Override
public void run(String... strings) throws Exception {
this.repository.save(new Employee("duke", "earl", "dude"));
}
}
Navigating to the console after application startup at localhost:8080/console shows jdbc:h2:~/test with only an INFORMATION_SCHEMA and users menu. I also set this up as a CRUD repository and, though I can post to it, none of the attribute data seems to be saved, but the Employees resource is recognized.
POST:{"firstName": "Bilbo", "lastName": "Baggxins", "description": "burglar"}
Comes back with:
{
"_links": {
"self": {
"href": "http://localhost:8080/api/employees/4"
},
"employee": {
"href": "http://localhost:8080/api/employees/4"
}
}
}
The default h2 url with Spring Boot is: jdbc:h2:mem:testdb
To use jdbc:h2:~/test you must add this to your application.properties:
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:~/test
What's happening is, you are writing the Employee in spring-boot's memory database (testdb). Then, you open the h2-console to jdbc:h2:~/test, which creates it on the fly, and let you browse emptiness.
With spring.h2.console.enabled=true you may open a browser to http://localhost:8080/h2-console and view the database content. Use the following settings:
Saved Settings: Generic H2 (Embedded)
Driver Class: org.h2.Driver
URL: jdbc:h2:mem:testdb
username: sa
password:
This is shamelessly borrowed from Josh Long. This is a working CommandLineRunner implementation. Github full code
#Component
class SampleRecordsCLR implements CommandLineRunner {
private final ReservationRepository reservationRepository;
#Autowired
public SampleRecordsCLR(ReservationRepository reservationRepository) {
this.reservationRepository = reservationRepository;
}
#Override
public void run(String... args) throws Exception {
Stream.of("Josh", "Jungryeol", "Nosung", "Hyobeom",
"Soeun", "Seunghue", "Peter", "Jooyong")
.forEach(name -> reservationRepository.save(new Reservation(name)));
reservationRepository.findAll().forEach(System.out::println);
}
}

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