Spring-Data-Mongodb NoSuchMethodError when writing to db - java

I'm building a spring webapp using mongodb but recently I began having problems with writing to DB. The following stack trace is what I get.
SEVERE: Servlet.service() for servlet [DispatcherServlet] in context with path [/afcrowther_blog] threw exception [Handler processing failed; nested exception is java.lang.NoSuchMethodError: org.springframework.data.mongodb.core.mapping.MongoPersistentProperty.isWritable()Z] with root cause
java.lang.NoSuchMethodError: org.springframework.data.mongodb.core.mapping.MongoPersistentProperty.isWritable()Z
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$3.doWithPersistentProperty(MappingMongoConverter.java:415)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$3.doWithPersistentProperty(MappingMongoConverter.java:412)
at org.springframework.data.mapping.model.BasicPersistentEntity.doWithProperties(BasicPersistentEntity.java:294)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeInternal(MappingMongoConverter.java:412)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeInternal(MappingMongoConverter.java:386)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.write(MappingMongoConverter.java:350)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.write(MappingMongoConverter.java:77)
at org.springframework.data.mongodb.core.MongoTemplate.toDbObject(MongoTemplate.java:732)
at org.springframework.data.mongodb.core.MongoTemplate.doInsert(MongoTemplate.java:714)
at org.springframework.data.mongodb.core.MongoTemplate.insert(MongoTemplate.java:672)
at org.springframework.data.mongodb.core.MongoTemplate.insert(MongoTemplate.java:663)
After reading up the most common cause of this seems to be dependency mismatches, but I'm not sure which dependencies are actually compatible with one another in that case.
Pom.xml
<spring.version>4.0.7.RELEASE</spring.version>
<jackson.version>1.9.2</jackson.version>
<spring.security.version>3.2.5.RELEASE</spring.security.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.12.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.6.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-libs-snapshot</id>
<name>Spring Snapshot Repository</name>
<url>http://repo.spring.io/libs-snapshot</url>
</repository>
</repositories>
<build>
<finalName>afcrowther blog</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
</plugins>
</build>
These are mainly the latest release versions, although I changed spring framework to 4.0.7.Release to try and fix it, but I have also used 4.1.0.Release and the same exception occurs.
Thanks
EDIT: #Document Annotated class that throws the error, role set as a String until this problem is resolved
#Document(collection = "user")
public class UserModel{
#PersistenceConstructor
public UserModel(String id, String firstName, String surname, String email,
String password, String role) {
this.id = id;
this.firstName = firstName;
this.surname = surname;
this.email = email;
this.password = password;
this.role = role;
}
public UserModel(){
}
#Id
private String id;
#Field("firstName")
#Indexed
private String firstName;
#Field("surname")
private String surname;
#Field("email")
#Indexed(unique = true)
private String email;
#Field("password")
private String password;
#Field("role")
private String role;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole(){
return role;
}
public void setRole(String role){
this.role = role;
}
}

Update on the question, Upon changing to spring bom and spring data bom dependency management, the problem persisted.
However, removing the "#PersistenceConstructor" tag from the first constructor, and then switching around the order of the constructors fixed the issue. So the default constructor has to be first one in the file by the look of things. Not sure why, but there you go!

Related

Send JSON Object from Postman to Restful webservices

For exercise I'm trying to make a POST call on postman having the following classes but it always gives me an error that it cannot read the data.
The GET give me back the various users in the db and the commented POST where I go to create the new user manually (ie by setting the strings "blabla") works. I would like my POST to take a json object from the postman body
{
"username": "1",
"password": "2",
"email": "3"
}
and sending the request I enter the new user in the db. How can I do?
UserDB.java
public class UserDB {
public void insertUser(User user) {
EntityManager entityManager = JPAUtil.getEntityManagerFactory().createEntityManager();
EntityTransaction entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
user.setUsername(user.getUsername());
user.setPassword(user.getPassword());
user.setEmail(user.getEmail());
entityManager.persist(user);
entityTransaction.commit();
}
User.java
#XmlRootElement(name = "user")
#XmlAccessorType(XmlAccessType.FIELD)
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id")
private int user_id;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#Column(name = "email")
private String email;
public User() {
}
public User(int user_id, String username, String password, String email) {
this.user_id = user_id;
this.username = username;
this.password = password;
this.email = email;
}
public User(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String passoword) {
this.password = passoword;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
RestUser.java
#Path("/users")
public class RestUser {
private UserDB userDB;
public RestUser() {
this.userDB = new UserDB();
}
#GET
#Produces(MediaType.APPLICATION_JSON)
public String getUsers_JSON() {
String listUser = null;
List<User> list = userDB.selectAllUsers();
Gson gson = new Gson();
listUser = gson.toJson(list);
return listUser;
}
#GET
#Path("/{id}")
#Produces(MediaType.APPLICATION_JSON)
public String getUser_byid(#PathParam("id") int id) {
String u = null;
User user = userDB.selectUser_ID(id);
Gson gson = new Gson();
u = gson.toJson(user);
return u;
}
/*
#POST
#Produces(MediaType.APPLICATION_JSON)
public String message() {
String u = null;
Gson gson = new Gson();
User user = new User("user", "sss", "sss");
u = gson.toJson(user);
userDB.insertUser(user);
return u;
}
*/
#POST
#Path("/insert")
#Produces(MediaType.APPLICATION_JSON)
public void createUser(#QueryParam("username") String username,#QueryParam("password") String password,#QueryParam("email") String email) {
User newuser = new User(username, password, email);
userDB.insertUser(newuser);
}
}
I add my pom.xml
<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>
<groupId>com.exercises</groupId>
<artifactId>UserManagement</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.9.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.6.9.Final</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.servlet.jsp.jstl</artifactId>
<version>1.2.5</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
<exclusion>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<finalName>UserManagement</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.2</version>
</plugin>
</plugins>
</build>
</project>
and my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<servlet>
<servlet-name>jerseyServlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>net.java.webservice</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jerseyServlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
In your controller method createUser you defined three query parameters for the user attributes instead of using the request body to receive the user data.
If you want to receive the user object as JSON in the request body try this:
#POST
#Path("/insert")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public void createUser(User user) {
userDB.insertUser(user);
}
Note the #Consumes annotation. When a HTTP POST request is sent to /users/insert (you could also leave /insert out, see below) the createUser method will be called and the JSON document with the user details will be converted into a Java object of the type User.
You can simplify it to:
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public void createUser(User user) {
userDB.insertUser(user);
}

Action cannot be cast to class java.lang.String

I keep getting this message:
29-Jul-2021 12:54:23.839 WARN [RMI TCP Connection(3)-127.0.0.1] org.hibernate.boot.internal.SessionFactoryOptionsBuilder. class org.hibernate.tool.schema.Action cannot be cast to class java.lang.String (org.hibernate.tool.schema.Action is in unnamed module of loader org.apache.catalina.loader.ParallelWebappClassLoader #1a92892d; java.lang.String is in module java.base of loader 'bootstrap') Ignoring
Why does it appear? How can I fix this?
Below is my entire project.
AppInit.class
public final class AppInit extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected final Class<?>[] getRootConfigClasses() {
return new Class<?>[]{ RootConfig.class };
}
#Override
protected final Class<?>[] getServletConfigClasses() {
return new Class<?>[] { Config.class };
}
#Override
protected final String [] getServletMappings() {
return new String[]{"/"};
}
}
Config.class
#EnableWebMvc
#Configuration
#ComponentScan("com.hiber.controller")
public class Config implements WebMvcConfigurer {
}
RootConfig.class
#EnableWebMvc
#Configuration
public class RootConfig implements WebMvcConfigurer{
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/hiber?serverTimezone=UTC&useSSL=false");
dataSource.setUsername("root");
dataSource.setPassword("1111");
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.hiber.model");
factory.setDataSource(dataSource());
factory.setJpaProperties(additionalProperties());
return factory;
}
#Bean
Properties additionalProperties() {
Properties properties = new Properties();
properties.put(Environment.SHOW_SQL, "true");
properties.put(Environment.FORMAT_SQL, "true");
properties.put(Environment.DEFAULT_SCHEMA, "hiber");
properties.put(Environment.HBM2DDL_AUTO, Action.UPDATE);
properties.put(Environment.DIALECT, "org.hibernate.dialect.MySQL8Dialect");
properties.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
return properties;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory);
return txManager;
}
}
Home.class
#Controller
public class Home {
#ResponseBody
#GetMapping(value = "/")
public String home () {
return "home";
}
}
User.class
#Entity(name = "User")
#Table(name = "user", schema = "hiber")
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, unique = true)
private Long id;
#NaturalId
#Column(name = "email")
private String email;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hiber</groupId>
<artifactId>Hiber</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${encoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<failOnMissingWebXml>false</failOnMissingWebXml>
<java.version>11</java.version>
<encoding>UTF-8</encoding>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>5.3.9</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>5.7.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Spring Framework-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<!-- Servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- Mysql connector java-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<!-- Spring data jpa-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.5.3</version>
</dependency>
<!-- Hibernate entity manager-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.5.4.Final</version>
</dependency>
<!-- Testing-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.20.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.11.2</version>
<scope>test</scope>
</dependency>
<!-- Logging-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.32</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.32</version>
</dependency>
</dependencies>
</project>
Tell me, what am I doing wrong?
Maybe it comes from duplicating dependency.
Please provide your pom.xml
I changed properties.put(Environment.HBM2DDL_AUTO, Action.UPDATE);
I changed properties.put(Environment.HBM2DDL_AUTO, Action.UPDATE); to properties.put(Environment.HBM2DDL_AUTO, "update");

Hibernate uses wrong column name despite all anotations

I am trying to configure simple database using Spring JPA, and I encountered, which seems simular to some questions here, but solution to this aren`t working.
I am trying to insert following POJO into PostgreSQL database :
#Entity
#Table(name = "students", schema = "public")
public class Student {
#Id
#Column(name = "ID")
private UUID id = UUID.randomUUID();
#Column(name = "First_Name")
private String firstName;
#Column(name = "Last_Name")
private String lastName;
#Column(name = "Age")
private Integer age;
#Column(name = "Passport_Number")
private Integer passNumber;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "Group_ID", referencedColumnName = "ID")
private Group group;
public UUID getId() {
return id;
}
public void setId(#NonNull UUID id) { this.id = id; }
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getPassNumber() {
return passNumber;
}
public void setPassNumber(Integer passNumber) {
this.passNumber = passNumber;
}
public Group getGroup() { return group; }
public void setGroup(Group group) { this.group = group; }
public void setUpdate(#NonNull Student student) {
setFirstName(student.getFirstName());
setLastName(student.getLastName());
setAge(student.getAge());
setPassNumber(student.getPassNumber());
}
}
Table of my database is created using following sql :
CREATE TABLE students (
"ID" UUID,
"First_Name" VARCHAR(50),
"Last_Name" VARCHAR(50),
"Age" INT,
"Passport_Number" INT,
"Group_ID" UUID,
UNIQUE("First_Name", "Last_Name"),
UNIQUE("Passport_Number"),
FOREIGN KEY("Group_ID") REFERENCES groups("ID"),
PRIMARY KEY ("ID")
);
When trying to insert new Student, Hibernate builds following sql (message in console) :
Hibernate:
select
student0_.ID as id1_0_0_,
student0_.Age as age2_0_0_,
student0_.First_Name as first_na3_0_0_,
student0_.Group_ID as group_id6_0_0_,
student0_.Last_Name as last_nam4_0_0_,
student0_.Passport_Number as passport5_0_0_
from
public.students student0_
where
student0_.ID=?
And here is the problem. There is no student0_, and so psql off course gives org.postgresql.util.PSQLException: ERROR: column student0_.id does not exist
I tryied also to give name variable to #Entity specifically, but to no effect. Also I tried to change naming stratagies : implicit naming strategy, improved naming strategy, physical naming strategy, implicit legacy naming strategy. And I already tried to change dialect, but also nothing.
My current hibernate properties are :
#Hibernate
hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto = none
hibernate.ejb.naming_strategy = org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
Also this is Configuration that I use :
#Configuration
#EnableTransactionManagement
#PropertySource({"classpath:dao.properties"})
#EnableJpaRepositories(basePackages = {"com.university.dao"})
public class ApplicationConfig {
#Autowired
private Environment environment;
public ApplicationConfig() {
super();
}
#Bean
public DataSource dataSource() {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(environment.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(environment.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(environment.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(environment.getProperty("jdbc.password")));
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource,
Environment environment) {
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(dataSource);
entityManagerFactory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManagerFactory.setJpaProperties(getHibernateProperties());
entityManagerFactory.setPackagesToScan("com.university.domain");
return entityManagerFactory;
}
#Bean
public PlatformTransactionManager transactionManager() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory(dataSource(),environment).getObject());
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties getHibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", environment.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", environment.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", environment.getProperty("hibernate.show_sql"));
hibernateProperties.setProperty("hibernate.format_sql", environment.getProperty("hibernate.format_sql"));
hibernateProperties.setProperty("hibernate.ejb.naming_strategy", environment.getProperty("hibernate.ejb.naming_strategy"));
return hibernateProperties;
}
}
As for versions, I am using Spring JPA 2.3.1.Release and Hibernate 5+, here is full maven pom 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>
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.3.1.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>university</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.build.reporting.outputEncoding>UTF-8</project.build.reporting.outputEncoding>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit-jupiter.version>5.6.1</junit-jupiter.version>
<junit.version>4.13</junit.version>
<org.springframework.version>5.2.7.RELEASE</org.springframework.version>
<org.springframework.boot.version>2.3.1.RELEASE</org.springframework.boot.version>
<org.hibernate.validator.version>6.1.5.Final</org.hibernate.validator.version>
<org.apache.tomcat.version>9.0.36</org.apache.tomcat.version>
<com.vaadin.version>16.0.0</com.vaadin.version>
<org.junit.jupiter.version>5.6.2</org.junit.jupiter.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M4</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>3.0.0-M1</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.university.Main</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${org.springframework.boot.version}</version>
</plugin>
<plugin>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-maven-plugin</artifactId>
<version>${com.vaadin.version}</version>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-bom</artifactId>
<version>${com.vaadin.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${org.springframework.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>${org.springframework.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${org.springframework.boot.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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>${org.springframework.boot.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${org.hibernate.validator.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>${org.apache.tomcat.version}</version>
</dependency>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-spring-boot-starter</artifactId>
<version>${com.vaadin.version}</version>
</dependency>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin</artifactId>
<version>${com.vaadin.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>29.0-jre</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.12.jre7</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${org.junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${org.junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${org.junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.stefanbirkner</groupId>
<artifactId>system-rules</artifactId>
<version>1.19.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-reflect</artifactId>
<version>2.0.7</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
How may I remove this error without explicitly(manually) rewriting hibernate queries in configuration (so hibernate would use correct column/table names automatically)?
Regardless if your answer/comment helps or not, thank you very much for your effort:)
There is a student0_, it's the table alias declared in from student student0_. It's the column that's not being found since it wasn't escaped properly, so student0_.ID really is treated as student0_.id.
Using case sensitive names isn't recommended in Postgres, whereas it's common with other databases. So instead of "First_name", just use first_name. Otherwise you need to escape the names everywhere e.g.
#Column(name = "\"First_Name\"")
and that's not pretty, and all other Postgres users will frown upon your database schema.

xml response not working but json is working Rest Api using Jersey

This is my first program on REST API using jersey. My rest API is giving me an Error code 500 when I try to get the response back in XML but it is working fine for JSON.
Can someone tell me what I am doing wrong?
There is no error shown in the console.
public class MyResource {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getIt() {
return "Got it!";
}
#GET
#Produces(MediaType.APPLICATION_XML)
#Path("/cust")
public Customer getCust() {
Customer cus= new Customer();
cus.setName("john");
cus.setId(1);
cus.setAddress("india");
return cus;
}
#GET
#Path("/test/order")
#Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public Order getOrder() {
List<Order> o =new ArrayList<Order>();
Order ord=new Order();
ord.setCost(0);
ord.setProductID(0);
ord.setQuantity(0);
ord.setShippingAddress("abcd");
o.add(ord);
return ord;
}
}
My customer class
package in.octalian.mobileservice.model;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Customer {
private int id;
private String name ;
private String address;
public Customer() {}
public Customer(int id,String name,String address) {
this.id=id;
this.name=name;
this.address=address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
my pom.xml
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>in.octalian</groupId>
<artifactId>mobileservice</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>mobileservice</name>
<build>
<finalName>mobileservice</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<inherited>true</inherited>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
<!-- uncomment this to get JSON support -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-binding</artifactId>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
<properties>
<jersey.version>2.27</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
XML response that I attach to give more information to you.
The issue is that you are trying to access a URI /cus but your code have a declaration as #Path("/cust"). So you should be using /cust.
Secondly, you could run your server(apache-tomcat for me) in debug mode to get debugging information if no logs are getting logged in the console for some error
Also, you need to add the header "Accept" in the request with the expected result format type. If not specified the first one will be considered as it appears first.

How to post json object in spring hibernate

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.

Categories

Resources