How to post json object in spring hibernate - java

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.

Related

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");

#MockMvc does not work with validation annotated with #Valid

None of these solutions helped here: Spring mockMvc doesn't consider validation in my test. Added all of these dependencies, nothing helps.
I use Spring Boot 2.1.2, pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<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-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<!-- Testing -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.springtestdbunit</groupId>
<artifactId>spring-test-dbunit</artifactId>
<version>1.3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.dbunit</groupId>
<artifactId>dbunit</artifactId>
<version>2.5.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-matchers</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
</dependencies>
I use standard hibernate validation '#NotNull':
#Entity
#Table(name="employee")
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Employee {
#Id
#Column
#GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
#NotNull(message = "Please provide name")
#Column(name = "name")
private String name;
#Column(name = "role")
private String role;
public Employee() {}
public Employee(String name, String role) {
this.name = name;
this.role = role;
}
}
#RestController
#RequestMapping(EmployeeController.PATH)
public class EmployeeController {
public final static String PATH = "/employees";
#Autowired
private EmployeeService service;
#PostMapping("")
public Employee newEmployee(#RequestBody #Valid Employee newEmployee) {
return service.save(newEmployee);
}
}
#Service
public class EmployeeService {
#Autowired
private EmployeeRepository repository;
public Employee save(Employee entity) {
return getRepository().save(entity);
}
}
#Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
Then I test my controller:
#RunWith(SpringRunner.class)
#SpringBootTest
#Transactional
#DatabaseSetup("/employee.xml")
#TestExecutionListeners({
TransactionalTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class,
DbUnitTestExecutionListener.class
})
public class EmployeeControllerWebApplicationTest {
#Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
private static String employeeRouteWithParam = EmployeeController.PATH + "/{id}";
#Before
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.build();
}
#Test
public void create_WithoutName_ShouldThrowException() throws Exception {
String role = "admin";
Employee expectedEmployee = new Employee(null, role);
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(expectedEmployee);
ResultActions resultActions = this.mockMvc.perform(post(PATH)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(json))
.andDo(print());
String contentAsString = resultActions.andReturn().getResponse().getContentAsString();
System.out.println("content: " + contentAsString); // empty body
resultActions
.andExpect(status().isBadRequest())
.andExpect(jsonPath("error").exists()) // not exist!!!
.andExpect(jsonPath("timestamp").exists()); // not exist!!!
}
}
employee.xml:
<dataset>
<Employee id="1" name="John" role="admin"/>
<Employee id="2" name="Mike" role="user"/>
</dataset>
I can not understand why it does not work when I test through #MockMvc. What am i doing wrong? Status is correct, but there is no error content, empty response
But validation works if tested on a really running application, then everything works.

Use JPA Spring boot with SQL Server

I want to use JPA in Spring boot with SQL Server by STS
This is my table:
MAVEN
<dependencies>
<dependency>
<groupId>com.hynnet</groupId>
<artifactId>sqljdbc-chs</artifactId>
<version>4.0.2206.100</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<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-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
application.properties
spring.datasource.driver-class- name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=quanlybanhang
spring.datasource.username=sa
spring.datasource.password=1
spring.jpa.hibernate.ddl-auto=create
spring.datasource.initialize=true
spring.jpa.database=SQL_SERVER
Model.Account.class
#Entity
#Table(name="taikhoan",uniqueConstraints=#UniqueConstraint(columnNames = { "tendangnhap" }) )
public class Account {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#NotNull
private String tendangnhap;
#NotNull
private String matkhau;
public Account(String tendangnhap, String matkhau) {
super();
this.tendangnhap = tendangnhap;
this.matkhau = matkhau;
}
public Account() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTendangnhap() {
return tendangnhap;
}
public void setTendangnhap(String tendangnhap) {
this.tendangnhap = tendangnhap;
}
public String getMatkhau() {
return matkhau;
}
public void setMatkhau(String matkhau) {
this.matkhau = matkhau;
}
}
interface AccountDAO
public interface AccountDAO extends JpaRepository<Account, Integer>{
}
ServiceAccount.class
#Service
public class ServerAccount {
#Autowired
AccountDAO server;
public void them(Account acc){
server.save(acc);
}
public List<Account> lietke(){
return server.findAll();
}
}
ServicesAccount.class
#Service
public class ServerAccount {
#Autowired
AccountDAO server;
Account acc=new Account("khang", "1");
public void addAccount(){
server.save(acc);
}
public List<Account> lietke(){
return server.findAll();
}
}
I called method addAccount() in Controller and this is Exception I got
"java.lang.NoClassDefFoundError: org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor"
"Caused by: java.lang.ClassNotFoundException: org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"
Please help me fix this exception. Thanks!!!
From your dependencies you missed (check you java version you use):
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.5.2.jre8-preview</version>
<scope>test</scope>
</dependency>
and into the application properties correct this line:
spring.datasource.driver-class- name=com.microsoft.sqlserver.jdbc.SQLServerDriver
to
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect

Spring-Data-Mongodb NoSuchMethodError when writing to db

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!

java.lang.NoSuchFieldError: name at run time in hibernate project

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.

Categories

Resources