Maven entry for SpEL as a ScriptEngine - spring

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;
}

Related

What is the cause of getting empty array list

I have 9 records in my database ,I want to fetch data using Id, I need
all the data of given ID, But when I try to fetch the data using JPQL
I am getting empty data in my console and my postman
Here is all the details of my code work
EmployeeRepository
package com.nilmani.workload.repository
import com.nilmani.workload.entity.Bank
import com.nilmani.workload.entity.Employee
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.web.bind.annotation.RequestParam
interface EmployeeRepository : JpaRepository<Employee,Long> {
#Query(" SELECT e.bankDetails from Employee e where e.id= :id")
fun findBankDetails(id: Long):Long
}
EmployeeController
package com.nilmani.workload.controller
import com.nilmani.workload.entity.*
import com.nilmani.workload.model.request.*
import com.nilmani.workload.model.response.*
import com.nilmani.workload.repository.*
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
#RestController
#RequestMapping("/test")
class ManagerController {
#Autowired
private lateinit var employeeRepository: EmployeeRepository
/**Get User details using UserId*/
#GetMapping("/my")
fun singleUser(#ModelAttribute request:ReqSingleUser){
val existUser:List<Employee> = employeeRepository.getEmployeesById(request.id)
existUser.forEach ({
println(existUser)
})
}
}
ModelClass
package com.nilmani.workload.model.request
data class ReqSingleUser(
val id:Long=-1
)
What is the reason for getting empty data,But already data present in
my database
I am using IntelliJ IDEA as code editor, mac as operating system
EmployeeEntityClass
package com.nilmani.workload.entity
import com.nilmani.workload.model.request.ReqBank
import javax.persistence.*
#Entity
data class Employee(
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
val id:Long=-1,
val name:String="",
val mobile:Long=-1,
#OneToOne(cascade = [CascadeType.ALL])
#JoinTable(
name = "emp_workstation",
joinColumns = [JoinColumn(name = "employee_id", referencedColumnName = "id")],
inverseJoinColumns = [JoinColumn(name = "bank_id", referencedColumnName = "id")]
)
val bankDetails: Bank,
val address:String=""
)

Is it possible to apply Save All Method as insert ignore method in JPA Repository?

I'm spring boot newbie so my knowledge is lacking.
I am using MySql with JPA repository in spring boot.
I put the data in an ArrayList and saved it using the "SaveAll" method.
I am trying to save by "insert ignore" method due to data conflict problem, is it possible?
Batch insert has been set and is being used.
Adding a custom insert query is very easy to do in Spring Data JPA. All we have to do is to annotate the entity with #SQLInsert.
And jpa repositories save and saveAll will take this insert query in consideration.
find here some documentation
Code sample :
import org.hibernate.annotations.SQLInsert;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
#Entity
#Table(name = "users")
#SQLInsert(sql = "INSERT IGNORE INTO users(first_name, last_name, email) " +
"VALUES (?, ?, ?)" )
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "first_name", nullable = false)
#NotBlank
#Size(max = 512)
private String firstName;
#Column(name = "last_name", nullable = false)
#NotBlank
#Size(max = 512)
private String lastName;
#Column(nullable = false)
#NotBlank
#Email
#Size(max = 512)
private String email;
But in my Opinion it is better to use native query for insertions
You could use an #Query annotation to define your own custom repo method to accomplish this
#Query("INSERT IGNORE INTO table (COLUMNS) values (...)")
public List<S> saveAllInsertIgnore(List<> list);

hibernate is not creating a table from model class

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

Can not use Kotlin to config Spring JPA Entity with Abstract Class

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 {

ModelMapper: Map geometries as GeoJson

I just found ModelMapper and I've found it very useful to generate DTOs.
Anyway, when it comes to serialize objects which own a JTS Geometry data type attribute, I'd want them to be in GeoJson format.
For the time being, the following class...
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.vividsolutions.jts.geom.MultiPolygon;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
#Entity
#Table(name = "municipios")
#Builder
#Data
#EqualsAndHashCode
#NoArgsConstructor
#AllArgsConstructor
public class Municipio implements Serializable {
/*
* Atributos
*/
#Transient
private static final long serialVersionUID = -2486158354849124667L;
#Id
private Integer gid;
private String codigo;
private String texto;
private MultiPolygon geom;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(
name = "cod_prov",
referencedColumnName = "codigo"
)
private Provincia provincia;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(
name = "cod_ccaa",
referencedColumnName = "codigo"
)
private ComunidadAutonoma comunidad;
}
...gets serialized as this...
"municipio": {
"gid": 27,
"codigo": "01036",
"texto": "Laudio/Llodio",
"provincia": {
"gid": 1,
"codigo": "01",
"texto": "Álava",
"texto_alt": "Araba",
"comunidad": {
"gid": 16,
"codigo": "16",
"texto": "País Vasco",
"texto_alt": "Euskadi"
}
},
"geom": "MULTIPOLYGON (((-2.9420491414616916 43.14380029306756, -2.9408165999002556 43.14430841999599, -2.939059950482368 43.141709610211024, -2.94050966386134 43.13799144046195, -2.936693413950487 43.13417138986535, -2.942182362664065 43.130752517734585, -2.943746497171919 43.126998320661244, -2.9491831049375983 43.122917261507745, -2.9568712631986553 43.11281715256084, -2.958883438671909 43.11305654097181, -2.9659615390025005 43.103108652799214, -2.9652067663290955 43.10264468267702, -2.9762492404051137 43.097150217253514, -2.9899968551814102 43.1013215781132, -2.9963369436287586 43.10706705889331, -3.0097035041930043 43.11278484125608, -3.0129149314121726 43.116877214910765, -3.017330715593204 43.116457973261085, -3.019790265011745 43.11919501110562, -3.02040901781778 43.12611504150391, -3.02393972418118 43.12847813412591, -3.025215180146138 43.13126035313113, -3.021643236846659 43.137154623532716, -3.013836762498057 43.1408026665335, -3.005568207272493 43.148466258438624, -3.0026147541242167 43.14959643860667, -2.9909328393119017 43.1625087272497, -2.9796315563151357 43.17050333013982, -2.9766664577130144 43.17485199744999, -2.9736646499823842 43.17600841462698, -2.979262791265818 43.18166902950952, -2.9742758156428035 43.18436486223879, -2.97110139733367 43.18276575229797, -2.969942290790593 43.179992017776314, -2.961893498167311 43.17338464369854, -2.957182021700495 43.17193318237574, -2.955167271064855 43.170041426431084, -2.9475444948015594 43.16848931161088, -2.955018585037522 43.157632918409604, -2.9474297891472103 43.151515433493785, -2.9420491414616916 43.14380029306756)))"
}
Is there any way to tell ModelMapper to map Geometries as GeoJSON objects when it comes to serializing objects?

Resources