How to mapping subquery in select with jpa - java

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 :)

Related

Failed to start bean 'documentationPluginsBootstrapper'; how can i fix it?

northwind/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.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>anilacar</groupId>
<artifactId>northwind</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>northwind</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>19.0.1</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Product.java
package anilacar.northwind.entities.concretes;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
#Data
#Entity
#Table(name = "products")
public class Product {
#Id //işlemleri primary keye göre yapar #Id olarak belirtmeliyiz
#GeneratedValue //sıralama işlemi için numaraları
#Column(name="product_id")
private int id ;
#Column(name="category_id")
private int categoryId;
#Column(name="product_name")
private String productName;
#Column(name="unit_price")
private double unitPrice ;
#Column(name="unit_in_stock")
private Integer unitsInStock;
#Column(name="quantity_per_unit")
private String quantityPerUnit;
public Product() {
}
public Product(int id, int categoryId, String productName, double unitPrice, Integer unitsInStock,
String quantityPerUnit) {
super();
this.id = id;
this.categoryId = categoryId;
this.productName = productName;
this.unitPrice = unitPrice;
this.unitsInStock = unitsInStock;
this.quantityPerUnit = quantityPerUnit;
}
}
ProductDao.java
package anilacar.northwind.dataAccess.abstracts;
import org.springframework.data.jpa.repository.JpaRepository;
import anilacar.northwind.entities.concretes.Product;
public interface ProductDao extends JpaRepository<Product, Integer>{
}
ProductsController.java
ProductManager.java
package anilacar.northwind.business.concretes;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import anilacar.northwind.business.abstracts.ProductService;
import anilacar.northwind.dataAccess.abstracts.ProductDao;
import anilacar.northwind.entities.concretes.Product;
#Service
public class ProductManager implements ProductService {
private ProductDao productDao;
#Autowired
public ProductManager(ProductDao productDao) {
super();
this.productDao = productDao;
}
#Override
public List<Product> getAll() {
return this.productDao.findAll();
}
}
ProductsController.java
package anilacar.northwind.api.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import anilacar.northwind.business.abstracts.ProductService;
import anilacar.northwind.entities.concretes.Product;
#RestController
#RequestMapping("api/products")
public class ProductsController {
private ProductService productService;
#Autowired
public ProductsController(ProductService productService) {
super();
this.productService = productService;
}
#GetMapping("/getall")
public List<Product> getAll(){
return this.productService.getAll();
}
}
How can ı fix this problem . Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null .

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.

Spring boot postgreSQL

I am writing a web app with Spring Boot, Hibernate and PostgreSQL. I want to learn how to save things in DB, but now I can`t resolve my problem. I am getting an error caused by my controller by line:
silniaRepository.save(silniaDB);
error is just:
java.lang.NullPointerException
there is my pom:
<name>silnia</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF- 8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.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.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.1.5.v20120716</version>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
part of my controller:
#Controller
public class SilniaController {
#Autowired
public SilniaService silniaService;
public SilniaRepository silniaRepository;
public SilniaDB silniaDB;
#RequestMapping("/db")
#ResponseBody
public String testMethod() {
StringBuilder response = new StringBuilder();
SilniaDB silniaDB = new SilniaDB()
.setNumber1(23);
silniaRepository.save(silniaDB);
for (SilniaDB i : silniaRepository.findAll()) {
response.append(i).append("<br>");
}
return response.toString();
}
my DB model:
#Entity
public class SilniaDB {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column
private int number;
public int getNumber() {
return number;
}
public void setNumber (int number){this.number=number;}
public SilniaDB setNumber1(int number) {
this.number = number;
return this;
}
public SilniaDB withNumber(final int number) {
this.number = number;
return this;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public String toString() {
return "TaskEntity{" +
"id=" + id +
"number=" + number +
'}';
}
}
and typical repository interface:
#Repository
public interface SilniaRepository extends CrudRepository<SilniaDB, Long> {
public SilniaDB findByNumber(Integer number);
}
I really spent a lot of time on that issue. Thanks in advance for every comment or answer.
Your repository is simply not being injected.
You have to put #Autowired for each of the dependencies individauly.
#Autowired
private SilniaService silniaService;
#Autowired
private SilniaRepository silniaRepository;
also make those fields as private..

Spring Boot + Hibernate + Postgres - not creating tables

I am trying to generate schema tables based on entities. The application starts correctly, the SQL is generated but there is no result - none of tables are created. What's wrong? I have used the same settings in plain Spring MVC + Hibernate JPA without Spring Boot and everything was working correctly.
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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.agileplayers</groupId>
<artifactId>applicationname</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>ApplicationName</name>
<description>Application Name</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<!--<scope>runtime</scope>-->
<version>9.4-1201-jdbc41</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties:
spring.datasource.url = jdbc:postgresql://localhost:5432/postgres
spring.datasource.driverClassName = org.postgresql.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQL82Dialect
spring.datasource.schema=schemaName
spring.datasource.username=userName
spring.datasource.password=userPassword
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
BaseEntity.java:
package com.agileplayers.applicationname.core.domain;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.util.Date;
#MappedSuperclass
public class BaseEntity {
#Id
#GeneratedValue
private int id;
private Date createdOn;
public String description;
public BaseEntity() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
example of Entity which extends BaseEntity - Entry.java:
package com.agileplayers.applicationname.core.domain;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import java.util.Date;
#Entity
public class Entry extends BaseEntity{
private String type;
#ManyToOne
private Account account;
public Entry() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
}
I have fixed the issue. Instead of spring.datasource.schema=schemaName there should be spring.jpa.properties.hibernate.default_schema=schemaName.
The set of necessary properties required for generating tables in my case is the following:
spring.datasource.url = jdbc:postgresql://localhost:5432/postgres
spring.jpa.properties.hibernate.default_schema = schemaName
spring.datasource.username = userName
spring.datasource.password = userPassword
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.show-sql = true

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