Trying my hand at my first hibernate (JPA annotations) console application. And I've been running around in circles trying to sort out dependencies, it feels like I'm trying to build a house of cards in a hurricane. Also, I'm using maven, I was under the impression that that maven is supposed to prevent this type of thing.. Anyways this is the error that I'm getting:
Exception in thread "main" java.lang.NoSuchFieldError: name
at org.slf4j.impl.Log4jLoggerAdapter.<init>(Log4jLoggerAdapter.java:75)
at org.slf4j.impl.Log4jLoggerFactory.getLogger(Log4jLoggerFactory.java:75)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:103)
at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:197)
at org.hibernate.ejb.Ejb3Configuration.<clinit>(Ejb3Configuration.java:107)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:124)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
at com.deangrobler.hibernatetest.App.main(App.java:14)
And this is my pom file:
<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.deangrobler</groupId>
<artifactId>HibernateTest</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>HibernateTest</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.4.0.GA</version>
<exclusions>
<exclusion>
<artifactId>ejb3-persistence</artifactId>
<groupId>org.hibernate</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
<exclusions>
<exclusion>
<artifactId>antlr</artifactId>
<groupId>antlr</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<version>1.1.1.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.5</version>
</dependency>
</dependencies>
</project>
And my annotated bean class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.deangrobler.hibernatetest;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author Dean Grobler
*/
#Entity
#Table(name = "user")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"),
#NamedQuery(name = "User.findById", query = "SELECT u FROM User u WHERE u.id = :id"),
#NamedQuery(name = "User.findByName", query = "SELECT u FROM User u WHERE u.name = :name")})
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Column(name = "name")
private String name;
public User() {
}
public User(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof User)) {
return false;
}
User other = (User) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.deangrobler.hibernatetest.User[ id=" + id + " ]";
}
}
If I can get some help on this I shall be eternally grateful!
You have two different version dependency for hibernate entity-manager. This will not work. Remove one of them
<dependency>
<groupId>hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.4.0.GA</version>
<exclusions>
<exclusion>
<artifactId>ejb3-persistence</artifactId>
<groupId>org.hibernate</groupId>
</exclusion>
</exclusions>
</dependency>
........................
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.10.Final</version>
</dependency>
try either deleting your slfj dependency entry in your pom, your force the hibernate dependency to exclude it. Hibernate wants to use its own.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.6.10.FINAL</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
<scope>compile</scope>
</dependency>
etc. Add the same exclusions for hibernate-core etc.
Seems to be a version conflict in the dependencies for artifact slf4j-log4j12.
You could check the output of "mvn dependency:tree" to check for a conflict.
Related
here is my UserController class
package ritu.login;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#Configuration
#RequestMapping("/vs1")
public class UserController {
#Autowired
UserService userService;
#GetMapping("/users")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
#GetMapping("/user/{id}")
private User getUser(#PathVariable("id") long id) {
return userService.getUserById(id);
}
#DeleteMapping("/user/{id}")
public void deleteUser(#PathVariable("id") long id) {
userService.delete(id);
}
#PostMapping("/users")
public long saveUser(#RequestBody User user) {
userService.saveOrUpdate(user);
return user.getId();
}
#PutMapping("/users")
public User Update(#RequestBody User users) {
userService.saveOrUpdate(users);
return users;
}
}
Here is UserService class
package ritu.login;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class UserService {
#Autowired
UserRepository userRepository;
public List<User> getAllUsers() {
List<User> users = new ArrayList<User>();
userRepository.findAll().forEach(user1 -> users.add(user1));
return users;
}
public User getUserById(long id) {
return userRepository.findById(id).get();
}
public void saveOrUpdate(User users) {
userRepository.save(users);
}
public void delete(long id) {
userRepository.deleteById(id);
}
public void update(User users, long id) {
userRepository.save(users);
}
}
here is my 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>ritu.login</groupId>
<artifactId>login-register</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>login-register</name>
<description>login example</description>
<properties>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-tomcat -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</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>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>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.10</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.10</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.30</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>6.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
here is my url in postman
http://localhost:8080/vs1/users
It gives error of 404 Not found..what should i do?
here is Pojo class
package ritu.login;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
#Entity
#ManagedBean(name = "loginBean")
#SessionScoped
#Component
public class User implements Serializable{
private static final long serialVersionUID = -7250065889869767422L;
#Id
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String validate(Long id,String name) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/any", "root", "jaygurudev1#");
PreparedStatement ps = con.prepareStatement("Select id,name from user where id=? and name=?");
ps.setLong(1, id);
ps.setString(2, name);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return "hello.xhtml";
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,
"Incorrect Username and Passowrd", "Please enter correct username and Password"));
return "index";
}
} catch (Exception e) {
System.out.println("in exception");
}
return null;
}
}
i saw some tutorial on javatpoint and other website but still the issue can't get solved.
what am i missing in the code or any version related issues?
IT GIVES 404 ERROR,WHILE HITTING URL
since,eclipse is showing error i have to add annotation.api jar in build path after that i have removed spring security dependency from pom.xml and it totally works
I try to create a website with spring. But when I try to coonect my project with my database and to work with it throw spring I get errors.I run mysql server only. I 100% know that port, password and username are right. What am I doing wrong?
run mysql server
sudo /etc/init.d/mysql start
like this
application.propeties:
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/java_spring_blog
spring.datasource.username=root
spring.datasource.password=root
dependcies:
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.coursework</groupId>
<artifactId>CourseWork</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>CourseWork</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Model:
package com.coursework.CourseWork.Models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Post {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title, anons, fulltext;
private int views;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAnons() {
return anons;
}
public void setAnons(String anons) {
this.anons = anons;
}
public String getFulltext() {
return fulltext;
}
public void setFulltext(String fulltext) {
this.fulltext = fulltext;
}
public int getViews() {
return views;
}
public void setViews(int views) {
this.views = views;
}
}
When I try to run programm I got an exeption:java.sql.SQLException: Access denied for user 'root'#'localhost'
And another one:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
I think it's because due to thirst one.
It works when I create a new user. Thanks to Ankit
I am developping a java/jee application using spring boot as framework and i want to filter entity application,so i tried to use querydsl and now i am trying to generate Q classes of querydsl.But when i make mvn install Q classes are not generated.i am using eclipse neon as ide and and java home is configured to JDK 8.
I am using jpa 2 and hibernate 5.
This is my code:
package biz.picosoft.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OrderColumn;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "application",uniqueConstraints = {#UniqueConstraint(columnNames = "reference")})
public class Application implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Column(name = "reference")
private String reference;
#Column(name = "creationDate")
private Date creationDate;
#Column(name = "status")
private String status;
#Column(name = "deadLine")
private Date deadLine;
#Column(name = "appType")
private String appType;
#Column(name = "projectId")
private Long projectId;
#OrderColumn(name = "listePiecesJointes")
private String[] listePiecesJointes;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getDeadLine() {
return deadLine;
}
public void setDeadLine(Date deadLine) {
this.deadLine = deadLine;
}
public String getAppType() {
return appType;
}
public void setAppType(String appType) {
this.appType = appType;
}
public Application() {
super();
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public Long getProjectId() {
return projectId;
}
public void setProjectId(Long projectId) {
this.projectId = projectId;
}
public String[] getListePiecesJointes() {
return listePiecesJointes;
}
public void setListePiecesJointes(String[] listePiecesJointes) {
this.listePiecesJointes = listePiecesJointes;
}
public Application(String reference, Date creationDate, String status, Date deadLine, String appType,String[] listePiecesJointes,Long projectId) {
super();
this.reference = reference;
this.creationDate = creationDate;
this.status = status;
this.deadLine = deadLine;
this.appType = appType;
this.projectId=projectId;
this.listePiecesJointes=listePiecesJointes;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((appType == null) ? 0 : appType.hashCode());
result = prime * result + ((creationDate == null) ? 0 : creationDate.hashCode());
result = prime * result + ((deadLine == null) ? 0 : deadLine.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((projectId == null) ? 0 : projectId.hashCode());
result = prime * result + ((reference == null) ? 0 : reference.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Application other = (Application) obj;
if (appType == null) {
if (other.appType != null)
return false;
} else if (!appType.equals(other.appType))
return false;
if (creationDate == null) {
if (other.creationDate != null)
return false;
} else if (!creationDate.equals(other.creationDate))
return false;
if (deadLine == null) {
if (other.deadLine != null)
return false;
} else if (!deadLine.equals(other.deadLine))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (projectId == null) {
if (other.projectId != null)
return false;
} else if (!projectId.equals(other.projectId))
return false;
if (reference == null) {
if (other.reference != null)
return false;
} else if (!reference.equals(other.reference))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
return true;
}
#Override
public String toString() {
return "Application [id=" + id + ", reference=" + reference + ", creationDate=" + creationDate + ", status="
+ status + ", deadLine=" + deadLine + ", appType=" + appType + ", projectId=" + projectId + "]";
}
}
this is my maven file
<?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>biz.picosoft</groupId>
<artifactId>gestionprojetback</artifactId>
<version>0.0.1</version>
<packaging>war</packaging>
<name>gestionprojetback</name>
<description>gestion de projet</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<start-class>biz.picosoft.ApplictationBoot</start-class>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<org.mysqlconnector-version>5.1.6</org.mysqlconnector-version>
<querydsl.version>4.1.4</querydsl.version>
<apt-maven-plugin.version>1.1.3</apt-maven-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<!--<scope>provided</scope> -->
</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-web-services</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${org.mysqlconnector-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-test -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>4.0.0.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.5</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mysema.querydsl/querydsl-apt -->
<!-- https://mvnrepository.com/artifact/com.mysema.querydsl/querydsl-apt -->
<!-- https://mvnrepository.com/artifact/com.querydsl/querydsl-apt -->
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>4.1.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>4.1.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Your configuration seems right.
Try this from Querydsl's documentation
If you use Eclipse, run mvn eclipse:eclipse to update your Eclipse project to include target/generated-sources/java as a source folder.
Now you are able to construct JPA query instances and instances of the query domain model.
You may also try Patrick's solution.
I am using spring ,jpa, hibernate,mysql , java 8,.In Dao (which is inteface and extends JpaRepository)
MyTable class
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
#Entity
#Table(name = "MY_TABLE")
public class MyTable {
#Id
#Column(name = "ID")
private long id;
#Column(name = "ITEM_NAME")
private String itemName;
#Column(name = "ITEM_PRICE")
private int itemPrice;
#Transient
private int col1;
public MyTable() {
}
public MyTable(long id, String itemName, int itemPrice, int col1) {
super();
this.id = id;
this.itemName = itemName;
this.itemPrice = itemPrice;
this.col1 = col1;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public int getItemPrice() {
return itemPrice;
}
public void setItemPrice(int itemPrice) {
this.itemPrice = itemPrice;
}
public int getCol1() {
return col1;
}
public void setCol1(int col1) {
this.col1 = col1;
}
}
MyTableDao
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.kolip.devchain.model.MyTable;
public interface MyTableDao extends JpaRepository<MyTable , Long> {
#Query(value = "SELECT mt.*, (select count(1) from anotherTable ) as col1 from MY_TABLE mt",nativeQuery = true)
List<MyTable> getMyTableList();
}
pom
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.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-security</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-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>com.github.stefanbirkner</groupId>
<artifactId>system-rules</artifactId>
<version>1.16.0</version>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate5</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
MY_TABLE
CREATE TABLE `my_table` (
`ID` bigint(20) NOT NULL,
`ITEM_NAME` varchar(255) DEFAULT NULL,
`ITEM_PRICE` int(11) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
I try to simplify my problem.I try to get col1 value but i can't find out how should be col1 attribute in entity. Other values can be gotten in entity.
If i use col1 attribute without #Transient , it will work , but col1 is not persistant(Also findAll() not working because there isn't col1 column on db). What should i do ?
you have many options but you could try this the following steps if you are using JPA 2.1:
1) Create a suitable DTO which should include properties that will take the results of your query:
"SELECT mt.*, (select count(1) from anotherTable ) as col1 from MY_TABLE mt"
2) In the MyTable entity, map the native query to your DTO using the #SqlResultSetMapping and #ConstructorResult annotations (a simple search on google will give you lots of usefull info on its usage).(See http://docs.oracle.com/javaee/7/api/javax/persistence/SqlResultSetMapping.html)
3) Modify the MyTableDao to use the native query you created in step 2.
I hope this helps. Goodluck :)
My pojo is
#Entity
#Table(name="userdetails")
public class UserDetails {
#Id
#Column(name="username")
private String username;
#Column(name="firstname")
private String firstname;
#Column(name="lastname")
private String lastname;
#Column(name="password")
private String password;}//getter and setter
RegisterInput class to store json object
#JsonSerialize
public class RegisterInput implements Serializable{
private static final long serialVersionUID = 1L;
private String username;
private String firstname;
private String lastname;
private String password;//getter and setters
My service class
#Transactional public void addUserDetails(UserDetails userDetails) {
userDetailsDao.addUserDetails(userDetails);
}
My Dao class
#Autowired
private SessionFactory sessionFactory;
public void addUserDetails(UserDetails userDetails) {
sessionFactory.getCurrentSession().save(userDetails);
}
My controller class
#RestController
#RequestMapping("/user")
public class UserDetailsController {
#Autowired
private UserDetailsService userDetailsService;
#RequestMapping(value="/details", method= RequestMethod.PUT ,
consumes= MediaType.APPLICATION_JSON_VALUE ,
produces= MediaType.APPLICATION_JSON_VALUE)
#ResponseBody public UserDetails addUserDetails(#RequestBody
RegisterInput registerInput)throws ValidationException{
if(registerInput==null || registerInput.getUsername()==null){
throw new ValidationException("Input is not valid");
}
UserDetails userDetails=new UserDetails(registerInput.getUsername(),
registerInput.getFirstname(), registerInput.getLastname(), registerInput.getPassword());
userDetailsService.addUserDetails(userDetails);
return userDetails;
}
My pom is
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!-- Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.4.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.10.Final</version>
</dependency>
I need to consume json object dynamically so that it gets stored to my database table. Any help would be apreciated. But whenever I pass json object to the resource mapping, it says error 415, media unsupported.