I am developping a java/jee application using spring boot as framework and i want to filter entity application,so i tried to use querydsl and now i am trying to generate Q classes of querydsl.But when i make mvn install Q classes are not generated.i am using eclipse neon as ide and and java home is configured to JDK 8.
I am using jpa 2 and hibernate 5.
This is my code:
package biz.picosoft.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OrderColumn;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "application",uniqueConstraints = {#UniqueConstraint(columnNames = "reference")})
public class Application implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Column(name = "reference")
private String reference;
#Column(name = "creationDate")
private Date creationDate;
#Column(name = "status")
private String status;
#Column(name = "deadLine")
private Date deadLine;
#Column(name = "appType")
private String appType;
#Column(name = "projectId")
private Long projectId;
#OrderColumn(name = "listePiecesJointes")
private String[] listePiecesJointes;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getDeadLine() {
return deadLine;
}
public void setDeadLine(Date deadLine) {
this.deadLine = deadLine;
}
public String getAppType() {
return appType;
}
public void setAppType(String appType) {
this.appType = appType;
}
public Application() {
super();
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public Long getProjectId() {
return projectId;
}
public void setProjectId(Long projectId) {
this.projectId = projectId;
}
public String[] getListePiecesJointes() {
return listePiecesJointes;
}
public void setListePiecesJointes(String[] listePiecesJointes) {
this.listePiecesJointes = listePiecesJointes;
}
public Application(String reference, Date creationDate, String status, Date deadLine, String appType,String[] listePiecesJointes,Long projectId) {
super();
this.reference = reference;
this.creationDate = creationDate;
this.status = status;
this.deadLine = deadLine;
this.appType = appType;
this.projectId=projectId;
this.listePiecesJointes=listePiecesJointes;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((appType == null) ? 0 : appType.hashCode());
result = prime * result + ((creationDate == null) ? 0 : creationDate.hashCode());
result = prime * result + ((deadLine == null) ? 0 : deadLine.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((projectId == null) ? 0 : projectId.hashCode());
result = prime * result + ((reference == null) ? 0 : reference.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Application other = (Application) obj;
if (appType == null) {
if (other.appType != null)
return false;
} else if (!appType.equals(other.appType))
return false;
if (creationDate == null) {
if (other.creationDate != null)
return false;
} else if (!creationDate.equals(other.creationDate))
return false;
if (deadLine == null) {
if (other.deadLine != null)
return false;
} else if (!deadLine.equals(other.deadLine))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (projectId == null) {
if (other.projectId != null)
return false;
} else if (!projectId.equals(other.projectId))
return false;
if (reference == null) {
if (other.reference != null)
return false;
} else if (!reference.equals(other.reference))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
return true;
}
#Override
public String toString() {
return "Application [id=" + id + ", reference=" + reference + ", creationDate=" + creationDate + ", status="
+ status + ", deadLine=" + deadLine + ", appType=" + appType + ", projectId=" + projectId + "]";
}
}
this is my maven file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>biz.picosoft</groupId>
<artifactId>gestionprojetback</artifactId>
<version>0.0.1</version>
<packaging>war</packaging>
<name>gestionprojetback</name>
<description>gestion de projet</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<start-class>biz.picosoft.ApplictationBoot</start-class>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<org.mysqlconnector-version>5.1.6</org.mysqlconnector-version>
<querydsl.version>4.1.4</querydsl.version>
<apt-maven-plugin.version>1.1.3</apt-maven-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<!--<scope>provided</scope> -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${org.mysqlconnector-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-test -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>4.0.0.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.5</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mysema.querydsl/querydsl-apt -->
<!-- https://mvnrepository.com/artifact/com.mysema.querydsl/querydsl-apt -->
<!-- https://mvnrepository.com/artifact/com.querydsl/querydsl-apt -->
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>4.1.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>4.1.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Your configuration seems right.
Try this from Querydsl's documentation
If you use Eclipse, run mvn eclipse:eclipse to update your Eclipse project to include target/generated-sources/java as a source folder.
Now you are able to construct JPA query instances and instances of the query domain model.
You may also try Patrick's solution.
Related
I have this entity
package com.example.demo;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.sql.Timestamp;
import java.util.Objects;
#Entity
public class Scanlog {
private String docId;
private String userName;
private Timestamp scanDate;
private Integer scanPlaza;
private long conteo;
#Id
#Column(name = "DOC_ID", nullable = false, length = 12)
public String getDocId() {
return docId;
}
public void setDocId(String docId) {
this.docId = docId;
}
#Basic
#Column(name = "USER_NAME", nullable = false, length = 20)
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Basic
#Column(name = "SCAN_DATE", nullable = false)
public Timestamp getScanDate() {
return scanDate;
}
public void setScanDate(Timestamp scanDate) {
this.scanDate = scanDate;
}
#Basic
#Column(name = "SCAN_PLAZA", nullable = true)
public Integer getScanPlaza() {
return scanPlaza;
}
public void setScanPlaza(Integer scanPlaza) {
this.scanPlaza = scanPlaza;
}
public Scanlog() {
}
public Scanlog(String docId, String userName, Timestamp scanDate, Integer scanPlaza) {
this.docId = docId;
this.userName = userName;
this.scanDate = scanDate;
this.scanPlaza = scanPlaza;
}
public Scanlog(String userName, long conteo) {
this.userName = userName;
this.conteo = conteo;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Scanlog scanlog = (Scanlog) o;
return Objects.equals(docId, scanlog.docId) && Objects.equals(userName, scanlog.userName) && Objects.equals(scanDate, scanlog.scanDate) && Objects.equals(scanPlaza, scanlog.scanPlaza);
}
#Override
public int hashCode() {
return Objects.hash(docId, userName, scanDate, scanPlaza);
}
}
and I have a class called apiDAOImpl like this:
package com.example.demo.dao;
import com.example.demo.Scanlog;
import com.example.demo.util.Conexion;
import javax.persistence.Query;
import java.sql.Date;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;
public class apiDAOImpl implements apiDAOLocal {
Conexion conexion = new Conexion();
#Override
public List<Scanlog> listScanSummary() {
List<Scanlog> json = new ArrayList<>();
try {
conexion.abrir();
Query q = conexion.em.createQuery("SELECT s.userName, count(s) from Scanlog s where DATE(s.scanDate) = current_date group by s.userName");
json = q.getResultList();
} catch (Exception e) {
e.printStackTrace();
} finally {
conexion.cerrar();
}
return json;
}
#Override
public List<Scanlog> listScanSummaryTest() {
List<Scanlog> json = new ArrayList<>();
try {
conexion.abrir();
Query q = conexion.em.createQuery("SELECT s from Scanlog s where DATE(s.scanDate) = current_date");
json = q.getResultList();
} catch (Exception e) {
e.printStackTrace();
} finally {
conexion.cerrar();
}
return json;
}
}
When I call the function listScanSummaryTest from my controller, this function is executed
Query q = conexion.em.createQuery("SELECT s from Scanlog s where DATE(s.scanDate) = current_date");
and I get something like this:
[
{
"docId": "22R110041369",
"userName": "HLOPEZ",
"scanDate": 1647267784991,
"scanPlaza": 1
},
{
"docId": "22R110041370",
"userName": "HLOPEZ",
"scanDate": 1647267785944,
"scanPlaza": 1
}
]
But when I call the function listScanSummary from my controller, I want this query to be executed:
Query q = conexion.em.createQuery("SELECT s.userName, count(s) from Scanlog s where DATE(s.scanDate) = current_date group by s.userName");
And I get this:
[
[
"HGLOPEZ",
118
],
[
"HLOPEZ",
298
]
]
and i would like to have something like this:
[
{
"userName": "HLOPEZ",
"count": 118
},
{
"userName": "HLOPEZ",
"count": 298
}
]
this is my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>1.0-SNAPSHOT</version>
<name>demo</name>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<junit.version>5.8.2</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0-PFD2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.5.Final</version>
</dependency>
<dependency>
<groupId>com.ibm.db2</groupId>
<artifactId>jcc</artifactId>
<version>11.5.7.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.13.1</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.1</version>
</plugin>
</plugins>
</build>
</project>
NOTE: i'm not using spring. Just javaee (1.8) and jpa
thanks for your help!!
As I said in my comment your query SELECT s.userName, count(s) from Scanlog s return a array of strings and in your test function you are selecting the entire object SELECT s from Scanlog s then the resutl is an array of object:
So if you want to return the expected result:
[
{
"userName": "HLOPEZ",
"count": 118
},
{
"userName": "HLOPEZ",
"count": 298
}
]
You have to create a model with userName and count attribut with a constructor which hold this fields.
Then in your query you can create an Object which took this fields.
For example :
Select new com.CustomObject(s.userName, count(s))
I am studying Spring Boot and I want to create a Rest Controller, and using a sql database, but there is a problem when I start the project :
Error:
(the error text is great I will leave the link)
And code:
OrderController.java
package ***;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.Optional;
#RestController
public class OrderController {
#Autowired
private OrderRepository orderRep;
#GetMapping("/")
public List<Order> index(){
return (List<Order>) orderRep.findAll();
}
#GetMapping("/{id}")
public Order show(#PathVariable int id){
Optional<Order> orderId= orderRep.findById(id);
Order order = orderId.get();
return order;
}
#PostMapping("/search")
public List<Order> search(#RequestBody Map<String, String> body){
String searchItem = body.get("item");
return orderRep.findByTitleContainingOrContentContaining(searchItem);
}
#PostMapping("/")
public Order create(#RequestBody Map<String, String> body){
String item = body.get("item");
int price = Integer.parseInt(body.get("price"));
int quantity = Integer.parseInt(body.get("quantity"));
return orderRep.save(new Order(item, price,quantity));
}
#PutMapping("/{id}")
public Order update(#PathVariable String id, #RequestBody Map<String, String> body){
int orderId = Integer.parseInt(id);
// getting blog
Optional<Order> order = orderRep.findById(orderId);
order.get().setItem(body.get("item"));
order.get().setPrice(Integer.parseInt(body.get("price")));
order.get().setQuantity(Integer.parseInt("quantity"));
return orderRep.save(order.get());
}
#DeleteMapping("/{id}")
public boolean delete(#PathVariable int id){
//int orderId = Integer.parseInt(id);
orderRep.deleteById(id);
return true;
}
}
Order.java
package ***;
import javax.persistence.*;
#Entity
#Table(name = "orders")
public class Order {
//Fields
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name = "item")
private String item;
#Column(name = "price")
private int price;
#Column(name = "quantity")
private int quantity;
//Constructors
public Order() { }
public Order(String item, int price, int quantity) {
this.setItem(item);
this.setPrice(price);
this.setQuantity(quantity);
}
public Order(int id, String item, int price, int quantity) {
this.setId(id);
this.setItem(item);
this.setPrice(price);
this.setQuantity(quantity);
}
//Object to string data
#Override
public String toString() {
return "Order{" +
"id=" + getId() +
", item='" + getItem() + '\'' +
", price='" + getPrice() + '\'' +
", price='" + getQuantity() + '\'' +
'}';
}
//Getters & Setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
OrderRepository.java
package ***;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface OrderRepository extends CrudRepository<Order, Integer> {
// custom query to search to blog post by title or content
List<Order> findByTitleContainingOrContentContaining(String item);
}
application.properties
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/testvoy?useUnicode=true&serverTimezone=UTC&useSSL=true&verifyServerCertificate=false
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name =com.mysql.jdbc.Driver
#spring.jpa.show-sql: true
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.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.test</groupId>
<artifactId>project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>project</name>
<description>project</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.8</version>
<executions>
<execution>
<id>generate-docs</id>
<phase>prepare-package</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>html</backend>
<doctype>book</doctype>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-asciidoctor</artifactId>
<version>${spring-restdocs.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I would be grateful for any help, thanks in advance
If you check the error, you can see that it comes from there:
List<Order> findByTitleContainingOrContentContaining(String item);
and if you read more closely to the error, you will see:
No property title found for type Order!;
inside here:
Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List com.test.project.OrderRepository.findByTitleContainingOrContentContaining(java.lang.String)! Reason: Failed to create query for method public abstract java.util.List com.test.project.OrderRepository.findByTitleContainingOrContentContaining(java.lang.String)! No property title found for type Order!; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List com.test.project.OrderRepository.findByTitleContainingOrContentContaining(java.lang.String)! No property title found for type Order!
Infact, if you check your model, there is no title property
Im making a Spring boot project and when running it says:
"Field trepository in com.example.trainerplanner.trainerController.TrainerController required a bean of type 'com.example.trainerplanner.model.domain.TrainerRepository' that could not be found."
I already cleaned the .m2 directory and tried to add/delete many different dependencies.
package com.example.trainerplanner;
#ComponentScan({"com.example.trainerplanner.model.domain"})
#EnableAutoConfiguration
#EnableJpaRepositories(basePackageClasses = {TrainerRepository.class, CategoryRepository.class})
#SpringBootApplication
public class TrainerplannerApplication {
private static final Logger log = LoggerFactory.getLogger(TrainerplannerApplication.class);
public static void main(String[] args) {
SpringApplication.run(TrainerplannerApplication.class, args);
}
#Bean
public CommandLineRunner trainerDemo(CategoryRepository crepository, TrainerRepository trepository) {
return (args) -> {
log.info("Save some exercises");
//Tässä kohdassa tehdään uudet kategoriat "c repositoryyn".
//Ensiksi on yläkropan päälihakset ja sitten alakropan
crepository.save(new Category("Biceps")); //Hauikset
crepository.save(new Category("Triceps")); //Ojentajat
crepository.save(new Category("Chest")); //Rinta
crepository.save(new Category("Shoulders")); //Olkapäät
crepository.save(new Category("Back")); //Selkä
crepository.save(new Category("Quadriceps")); //Etureidet
crepository.save(new Category("Hamstrings")); //Takareidet
crepository.save(new Category("Calves")); //Pohkeet
crepository.save(new Category("Glutes")); //Pakarat
trepository.save(new Trainer("Bicep curl", 8, 3, crepository.findByName("Biceps").get(0)));
trepository.save(new Trainer("Tricep extension", 8, 3, crepository.findByName("Triceps").get(0)));
trepository.save(new Trainer("Squat", 8, 3, crepository.findByName("Quadriceps").get(0)));
User userYksi = new User("user", "$2y$12$4iGWyQs5hC6ibe5Pq7ochekppUZcSfeIV.tjgZIuSobVA8B5vOhXK", "USER");
//Molemmat salasanat hashattu BCryptillä, roundit oli 12 ja 9
User userKaksi = new User("admin", "$2y$06$K9UJzObPGyroQKlkTzWWz.BlUurpYCMFelyvM/2AVYSbzogvd3.zq", "ADMIN");
urepository.save(userYksi);
urepository.save(userKaksi);
log.info("fetch all exercises");
for (Trainer trainer : trepository.findAll()) {
log.info(trainer.toString());
};
};}
This is the springbootapp
#Controller
#Component
#EnableJpaRepositories
public class TrainerController {
#Autowired
private TrainerRepository trepository;
#Autowired
private CategoryRepository crepository;
//Req. mappingeissä nähdään mikä menee urlin loppuun. esim. localhost:8080/trainerlist palauttaa trainerlist thymeleafsivun
//Metodit eri toiminnoille, esim lisää, poista, lista, tallenna.
#RequestMapping(value= {"/", "/trainerlist"})
public String trainerList(Model model) {
model.addAttribute("trainers", trepository.findAll());
return "trainerlist";
}
#RequestMapping(value = "/add")
public String addTrainer(Model model){
model.addAttribute("trainer", new Trainer());
model.addAttribute("category", crepository.findAll());
return "addtrainer";
}
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(Trainer trainer){
trepository.save(trainer);
return "redirect:trainerlist";
}
//Poistaa ID:n avulla trainerin ja palauttaa //trainerlist-sivun
#RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public String deleteTrainer(#PathVariable("id") Long trainerId, Model model) {
trepository.deleteById(trainerId);
return "redirect:../trainerlist";
}
}
Controller class
#Repository
public interface CategoryRepository extends CrudRepository<Category, Long> {
List<Category> findByName(String name);
}
CategoryRepo, TrainerREpo is same but with different name.
#Component
public class TrainerModel {
public String Trainer(#RequestParam(value="name")String name, Integer reps, Integer sets, Model model) {
model.addAttribute("name", name);
model.addAttribute("reps", reps);
model.addAttribute("sets", sets);
return "index";
}
}
This is the TrainerModel class
#Component
#Entity
public class Trainer {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private String name;
private Integer reps, sets;
#ManyToOne
#JoinColumn(name = "categoryid")
#JsonManagedReference
private Category category;
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public Trainer() {
//Tyhjä
}
public Trainer(String name, Integer reps, Integer sets, Category category) {
super();
this.name = name;
this.reps = reps;
this.sets = sets;
this.category =category;
}
//Asetetaan getterit ja setterit Traineriin.
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getReps() {
return reps;
}
public void setReps(Integer reps) {
this.reps = reps;
}
public Integer getSets() {
return sets;
}
public void setSets(Integer sets) {
this.sets = sets;
}
#Override
public String toString() { //Jos kategoria tyhjä niin palautetaan ensimmäinen kohta, muuten else-kohta.
if (this.category != null)
return "Trainer [id=" + id + ", name=" + name + ", reps=" + reps + ", =" + sets + " sets =" + this.getCategory() + "]";
else
return "Trainer [id=" + id + ", name=" + name + ", reps=" + reps + ", sets=" + sets + "]";
}
}
And This is the Trainer class
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>trainerplanner</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>trainerplanner</name>
<description>Trainer planner for exercising</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</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-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Pom xml, re did the whole project with spring initialzr but no effect.
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..
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 :)