I am trying to build an app using angular and spring MVC.
I have included the properties like so:
In stacktrace :
I am getting till:
Dec 19, 2021 6:25:36 PM org.apache.catalina.startup.Catalina start
I am not getting starting from this:
Spring WebApplicationInitializers detected on classpath
```
#SqlServer properties
spring.datasource.driver =
com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url = jdbc:sqlserver://localhost:1433/bookapi
spring.datasource.user = SA
spring.datasource.password = AccessSQL#21
#Hibernate properties
hibernate.show_sql = true
spring.jpa.hibernate.ddl_auto = create
spring.datasource.initialiazation-mode=always
#c3p0 properties
hibernate.c3p0.min_size = 5
hibernate.c3p0.max_size = 20
hibernate.c3p0.acquire_increment = 1
hibernate.c3p0.timeout = 1800
hibernate.c3p0.max_statements = 150
```
package com.bookapi.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Book")
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String title;
private String author;
public long getId() {
return id;
}
https://github.com/web-dot/Angular-Springmvc-bookapp
You need to set hibernate.dialect=org.hibernate.dialect.SQLServerDialect and please use just one #ComponentScan, for example #ComponentScan(basePackages = "com.bookapi")
Related
Well I just started learning spring boot, I work for the moment on a little project inserting Data into Database.
This is understood that "Id" shall be self created since I've include #GeneratedValue method. The problem is Intellij auto assigned property names to my data, which is prevent data entering to the database,i copy also image
Due to this auto property assigning act by intellij I'm unable to enter data in to database & getting an error (this is what I understand):
/home/kash/Documents/test/demos/src/main/java/com/example/demos/StudentConfig.java:18:32
java: constructor Student in class com.example.demos.Student cannot be applied to given
types;
required:
java.lang.Long,java.lang.String,java.lang.String,java.time.LocalDate,java.lang.Integer
found: java.lang.String,java.lang.String,java.time.LocalDate,int
reason: actual and formal argument lists differ in length
I'm looking for an advise, grateful for the help I copy all the script hereunder.
Student.java
package com.example.demos;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDate;
#Getter
#Setter
#AllArgsConstructor
#Entity
#Table
public class Student {
#Id
#SequenceGenerator(
name = "student_sequence",
sequenceName = "student_sequence",
allocationSize = 1
)
#GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "student_sequence"
)
private Long id;
private String name;
private String email;
private LocalDate dob;
private Integer age;
}
StudentRepository.java
package com.example.demos;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface StudentRepository
extends JpaRepository <Student, Long> {
}
StudentService.java
package com.example.demos;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.Month;
import java.util.List;
#Service
#AllArgsConstructor
public class StudentService {
#Autowired
private final StudentRepository studentRepository;
List<Student> getStudents(){
return studentRepository.findAll();
}
}
StudentConfig.java
package com.example.demos;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.LocalDate;
import java.util.List;
import static java.util.Calendar.MAY;
#Configuration
public class StudentConfig {
#Bean
CommandLineRunner commandLineRunner(
StudentRepository repository){
return args -> {
Student John = new Student(
"John Doe",
"john#hotmail.com",
LocalDate.of(2010, MAY, 19 ),
11
);
Student Haider = new Student(
"Haider",
"Haider#hotmail.com",
LocalDate.of(2024, MAY, 10 ),
2
);
repository.saveAll(
List.of(John, Haider)
);
};
}
}
I have created simple spring boot application in Intellij.
I have created Entity Class in that when i write #Id, #Column annotations it is giving error saying annotations not allowed here.
i tried so many different post from stack overflow but my problem not got resolved.
can someone please help on this.
package com.ajinkya.h2demo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "ROOM")
public class Room {
#Id
#Column(name = "ROOM_ID")
}
The error appears, because you haven't added any field below the annotations. After you add the field, the error will disappear.
#Id
#Column(name = "ROOM_ID")
private int roomId;
If you go to Column.java in java.persistencepackage you will find this declaration
...
* #since 1.0
*/
#Target({METHOD, FIELD})
#Retention(RUNTIME)
public #interface Column {
...
}
This indicated that #Column annotation can only be applied to methods and fields.
Hence in your entity class you would apply it to method or field like below
#Column(name = "is_active")
protected boolean active = true;
or
#Column(name = "is_active")
public boolean isActive() {
return active;
}
I am trying to use Kotlin in Spring project and I found that with entities extends abstract class. Kotlin can not tell the annotation in abstract class. The configuration is as below.
Base.kt
package io.qiyue.dream.entity
import org.hibernate.annotations.GenericGenerator
import org.springframework.data.annotation.CreatedBy
import org.springframework.data.annotation.LastModifiedBy
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.time.LocalDateTime
import javax.persistence.Column
import javax.persistence.EntityListeners
import javax.persistence.GeneratedValue
import javax.persistence.Id
#EntityListeners(AuditingEntityListener::class)
abstract class Base {
#Id
#GeneratedValue(generator = "UUID")
#GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
#Column(name = "id")
open var id: String? = null
#Column(name = "last_modified_at")
#LastModifiedDate
open val lastModifiedAt: LocalDateTime? = null
#Column(name = "last_modified_by")
#LastModifiedBy
open val lastModifiedBy: String? = null
#Column(name = "created_by")
#CreatedBy
open val createdBy: String? = null
}
Role.kt
package io.qiyue.dream.entity
import javax.persistence.*
#Entity
#Table(name = "q_role")
open class Role (val name: String) : Base(){
}
This would also not work in Java.
You need to add #MappedSuperclass to your base class to tell JPA that it must include all properties from the base class:
#EntityListeners(AuditingEntityListener::class)
#MappedSuperclass
abstract class Base {
Can you please point me to maven dependency to add the SpEL - Spring Expression Language - as a ScriptEngine to my project - is there any in Spring?)
I've found some examples:
https://gist.github.com/maggandalf/1380124
https://github.com/melin/starflow/blob/master/src/main/java/com/googlecode/starflow/core/script/spel/SpelScriptEngine.java
The code in examples show how to wrap SpEL as a JSR-223 scripting engine and make it available to scripting manager by name (say, "spel").
But I'd like it in a form of maven dependency.
I don't know if I understand you correctly, but try this
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
If pom.xml has this dependency only, the code in the package
https://github.com/melin/starflow/blob/master/src/main/java/com/googlecode/starflow/core/script/spel/
should compile with JDK1.8.
(replace 4.3.3.RELEASE with another version if there is a need).
I've just tried https://github.com/eobermuhlner/spel-scriptengine
You just need too add this to your pom.xml
<dependency>
<groupId>ch.obermuhlner</groupId>
<artifactId>spel-scriptengine</artifactId>
<version>1.0.0</version>
</dependency>
And then use it with Hibernate Validator like this:
package org.eu.rubensa.model;
import java.time.Instant;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.ScriptAssert;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
#Entity
#Table(name = "sample")
#Data
#EqualsAndHashCode(callSuper = false)
#NoArgsConstructor
#AllArgsConstructor
#ScriptAssert.List({
// Month valiadation
#ScriptAssert(lang = "spel", alias = "_this", script = "#_this.getLower() == null || #_this.getHigher() == null || #_this.getHigher().compareTo(#_this.getLower()) >= 0", reportOn = "finalMonth", message = "{org.eu.rubensa.validation.LowerGreaterThanHigher.message}"),
// Instant validation
#ScriptAssert(lang = "spel", alias = "_this", script = "#_this.getStart() == null || #_this.getEnd() == null || #_this.getEnd().compareTo(#_this.getStart()) >= 0", reportOn = "fechaFinPresentacion", message = "{org.eu.rubensa.validation.StartGreaterThanEnd.message}") })
public class SampleEntity {
#Id
#Column(name = "id", nullable = false)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sample_seq")
#SequenceGenerator(name = "sample_seq", sequenceName = "sample_seq", allocationSize = 1)
private Long id;
#Column(name = "lower", nullable = false)
#NotNull
#Min(1)
private Integer lower;
#Column(name = "higher", nullable = false)
#NotNull
#Min(1)
private Integer higher;
#Column(name = "start", nullable = true)
private Instant start;
#Column(name = "end", nullable = true)
private Instant end;
}
I'm using GWT RequestFactory + Hibernate + Spring in my web app.
I have Principal and Profile entities that relate to each other as one to one. They share the same primary key.
On a client side I write such a code, which causes NullPointerException:
If I exclude "principal.setProfile(profile);" code line, principal entity will be stored successfully. I can't figure out why profile entity can't be stored along with principal.
Any suggestions will be highly appreciated. Thanks in advance!
public RegistrationPanel() {
TarantulaFactory factory = GWT.create(TarantulaFactory.class);
factory.initialize(new SimpleEventBus());
PrincipalRequestContext principalCtx = factory.createPrincipalRequest();
ProfileRequestContext profileCtx = factory.createProfileRequest();
PrincipalProxy principal = principalCtx.create(PrincipalProxy.class);
principal.setLogin("Billy");
principal.setPassword("Corgan");
ProfileProxy profile = profileCtx.create(ProfileProxy.class);
profile.setNickname("A");
profile.setName("b");
profile.setEmail("ABCD34#gmail.com");
profile.setBirthDate(new Date());
profile.setCurrentLocation("Chicago");
principal.setProfile(profile);
profile.setPrincipal(principal);
principalCtx.save(principal).fire();
}
Stack trace:
//------------------------------------------------------------------------
21:09:24.992 [ERROR] [application] Uncaught exception escaped
java.lang.NullPointerException: null
at com.google.web.bindery.requestfactory.shared.impl.AbstractRequestContext$MyConstraintViolation.<init>(AbstractRequestContext.java:434)
at com.google.web.bindery.requestfactory.shared.impl.AbstractRequestContext$StandardPayloadDialect.processPayload(AbstractRequestContext.java:366)
at com.google.web.bindery.requestfactory.shared.impl.AbstractRequestContext$5.onTransportSuccess(AbstractRequestContext.java:1151)
at com.google.web.bindery.requestfactory.gwt.client.DefaultRequestTransport$1.onResponseReceived(DefaultRequestTransport.java:136)
at com.google.gwt.http.client.Request.fireOnResponseReceived(Request.java:258)
at com.google.gwt.http.client.RequestBuilder$1.onReadyStateChange(RequestBuilder.java:412)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:338)
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:219)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:571)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:279)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:242)
at sun.reflect.GeneratedMethodAccessor35.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:293)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:547)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
at java.lang.Thread.run(Thread.java:722)
//------------------------------------------------------------------------
Below is the source code for entities, proxies and RequestFactory.
Here are entity classes:
Profile.java
package com.szybieka.tarantula.core.domain;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
/**
*
* A Profile representing the user profile entity. Each user has single profile.
* Profile and {#link Principal} entities relate to each other as one-to-one.
* Shared primary key is used to join corresponding tables.
*
* #author Zmicer Szybieka
*
*/
#Entity
#Table(name = "profile", uniqueConstraints = { #UniqueConstraint(
columnNames = "id") })
public class Profile {
#Id
#NotNull
#Column(name = "id", unique = true)
#GeneratedValue(generator = "gen")
#GenericGenerator(name = "gen", strategy = "foreign",
parameters = #Parameter(name = "property", value = "principal"))
private Long id;
#Length(min = 1, max = 30)
private String nickname;
#Length(max = 30)
private String name;
#Column(name = "birth_date")
private Date birthDate; // date of birth, e.g. "20.01.1985"
#Length(max = 30)
#Column(name = "current_location")
private String currentLocation; // current location city, e.g. "NYC"
#Email
private String email;
private Date version;
#OneToOne(mappedBy = "profile", cascade = CascadeType.ALL)
private Principal principal; // the user principal corresponding to the
// profile
public Profile() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
// omit setters/getters
}
Principal.java
package com.szybieka.tarantula.core.domain;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.hibernate.validator.constraints.Length;
/**
* A Principal representing an identity used to determine access rights to
* application. Principal relates to {#link Profile} entity as one-to-one.
* Shared primary key is used to join corresponding tables.
*
* #author Zmicer Szybieka
*
*/
#Entity
#Table(name = "principal", uniqueConstraints = { #UniqueConstraint(
columnNames = "id") })
public class Principal {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Length(max = 20)
private String login;
#Length(max = 10)
private String password;
private Date version;
#OneToOne(cascade = CascadeType.ALL)
#PrimaryKeyJoinColumn
private Profile profile;
public Principal() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
// omit setters/getters
}
I use RequestFactory to connect with server side.
Here is my RequestFactory:
TarantulaFactory.java
package com.szybieka.tarantula.gwt.client.requestfactory;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.web.bindery.requestfactory.shared.RequestContext;
import com.google.web.bindery.requestfactory.shared.RequestFactory;
import com.google.web.bindery.requestfactory.shared.Service;
import com.szybieka.tarantula.gwt.client.proxy.PrincipalProxy;
import com.szybieka.tarantula.gwt.client.proxy.ProfileProxy;
import com.szybieka.tarantula.gwt.server.locator.PrincipalServiceLocator;
import com.szybieka.tarantula.gwt.server.locator.ProfileServiceLocator;
import com.szybieka.tarantula.gwt.server.service.PrincipalService;
import com.szybieka.tarantula.gwt.server.service.ProfileService;
public interface TarantulaFactory extends RequestFactory {
PrincipalRequestContext createPrincipalRequest();
ProfileRequestContext createProfileRequest();
#Service(value = ProfileService.class,
locator = ProfileServiceLocator.class)
public interface ProfileRequestContext extends RequestContext {
Request<Void> save(ProfileProxy profile);
Request<ProfileProxy> findProfile(Long id);
}
#Service(value = PrincipalService.class,
locator = PrincipalServiceLocator.class)
public interface PrincipalRequestContext extends RequestContext {
Request<PrincipalProxy> findPrincipal(String login, String password);
Request<PrincipalProxy> findPrincipal(Long id);
Request<PrincipalProxy> findPrincipalByLogin(String login);
Request<Void> save(PrincipalProxy principal);
Request<Void> remove(PrincipalProxy principal);
}
}
Here are proxies for entity classes:
ProfileProxy.java
package com.szybieka.tarantula.gwt.client.proxy;
import java.util.Date;
import com.google.web.bindery.requestfactory.shared.EntityProxy;
import com.google.web.bindery.requestfactory.shared.ProxyFor;
import com.szybieka.tarantula.core.domain.Profile;
import com.szybieka.tarantula.gwt.server.locator.ProfileLocator;
#ProxyFor(value = Profile.class, locator = ProfileLocator.class)
public interface ProfileProxy extends EntityProxy {
Long getId();
void setId(Long id);
// omit other getter/setter methods
}
PrincipalProxy.java
package com.szybieka.tarantula.gwt.client.proxy;
import com.google.web.bindery.requestfactory.shared.EntityProxy;
import com.google.web.bindery.requestfactory.shared.ProxyFor;
import com.szybieka.tarantula.core.domain.Principal;
import com.szybieka.tarantula.gwt.server.locator.PrincipalLocator;
#ProxyFor(value = Principal.class, locator = PrincipalLocator.class)
public interface PrincipalProxy extends EntityProxy {
Long getId();
String getLogin();
// omit other getter/setter methods
}
A RequestContext is a builder for a batch request that you eventually fire to send to the server for processing. All proxies have to be created and edited from the same RequestContext in a batch request.
Remove your use of ProfileRequestContext and replace profileCtx.create(ProfileProxy.class) with principalCtx.create(ProfileProxy.class).