Exception Could not resolve placeholder - spring

In general, I will try to describe the problem. A working project stopped working at one point. Revised and tried many options with from other posts until nothing helped. That's what comes out:
Caused by: org.hibernate.exception.SQLGrammarException: could not prepare statement
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Tabelle "USER" nicht gefunden
Table "USER" not found; SQL statement:
insert into user (ID, AKTIV, PASSWORD, START, USERROLE, USERNAME, VERSION) values (null, ?, ?, ?, ?, ?, ?) [42102-200]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:453)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:429)
at org.h2.message.DbException.get(DbException.java:205)
at org.h2.message.DbException.get(DbException.java:181)
at org.h2.command.Parser.readTableOrView(Parser.java:7628)
at org.h2.command.Parser.readTableOrView(Parser.java:7599)
at org.h2.command.Parser.parseInsert(Parser.java:1747)
at org.h2.command.Parser.parsePrepared(Parser.java:954)
at org.h2.command.Parser.parse(Parser.java:843)
at org.h2.command.Parser.parse(Parser.java:815)
at org.h2.command.Parser.prepareCommand(Parser.java:738)
at org.h2.engine.Session.prepareLocal(Session.java:657)
at org.h2.engine.Session.prepareCommand(Session.java:595)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1235)
at org.h2.jdbc.JdbcPreparedStatement.<init>(JdbcPreparedStatement.java:76)
at org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:1154)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$2.doPrepare(StatementPreparerImpl.java:109)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:176)
... 135 common frames omitted`
Here is the class code:
#Getter
#Setter
#NoArgsConstructor
#EqualsAndHashCode
#Entity
#Table(name = "user")
public class UserEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column( name = "ID" )
private Long id;
#Version
#Column( name = "VERSION")
private int version;
#Column( name = "USERNAME" )
private String username;
#Column( name = "PASSWORD" )
private String password;
#Column( name = "START" )
private String start;
#Column( name = "AKTIV" )
private String aktiv;
#Column( name = "USERROLE" )
private String userRole;
#OneToOne(mappedBy = "user")
private EmployeeEntity employeeEntity;
}
Tests stopped working, throwing the following error. The file is on the path: src/main/resources
Caused by: java.io.FileNotFoundException: class path resource [application.properties] cannot be opened because it does not exist
Here is the integration of the file into the project:
#EnableJpaRepositories(basePackages = "com.m_landalex.dataconvert.petsistence")
#ComponentScan(basePackages = "com.m_landalex.dataconvert")
#PropertySource("classpath:application.properties")
#Configuration
public class AppServiceConfig { ... }
After a small revision, a new error appears. The feeling is that Maven does not see my resource folders.
#EnableJpaRepositories(basePackages = "com.m_landalex.dataconvert.petsistence")
#ComponentScan(basePackages = "com.m_landalex.dataconvert")
#PropertySource(value = "classpath:application.properties", ignoreResourceNotFound = true)
#Configuration
public class AppServiceConfig { ... }
The file is on the path: src/test/resources/db
Exception:
Caused by: java.io.FileNotFoundException: class path resource [db/clean-up.sql] cannot be opened because it does not exist
Caused by: java.io.FileNotFoundException: class path resource [db/test-data.sql] cannot be opened because it does not exist
Test method:
#SqlGroup( { #Sql( value = "classpath:db/test-data.sql",
config = #SqlConfig( encoding = "utf-8", separator = ";", commentPrefix = "--" ),
executionPhase = ExecutionPhase.BEFORE_TEST_METHOD ),
#Sql( value = "classpath:db/clean-up.sql",
config = #SqlConfig( encoding = "utf-8", separator = ";", commentPrefix = "--" ),
executionPhase = ExecutionPhase.AFTER_TEST_METHOD) } )
#Test
public void fetchAllTest() {
List<AbstractObject> returnedList = defaultService.fetchAll();
assertNotNull(returnedList);
assertEquals(2, returnedList.size());
}
After adding
#Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
the application started to run. My tests remained a problem -
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'h2.hibernate.dialect' in value "${h2.hibernate.dialect}"
and the same configuration file is used

user is a reserved keyword, so you must use square brackets to make it explicit that you mean the object named "user" it, i.e. use [user] instead of user.

Related

issue saving record with Composite Key with one Generated value column : spring data jpa + DB2

i have a table in DB2 with name as policy this table has a composite primary key with columns : policy_id, context_cd.
policy_id is marked as always generated.
i am using spring boot with spring data jpa ,
Dialect i am using is org.hibernate.dialect.DB2Dialect in the properties file.
i have prepared the entity as below for the table policy
#Entity
#Data
#Table(name = "POLICY", schema = "...")
#IdClass(value = IdGenerationIdentity.class)
public class Policy {
// #EmbeddedId
// private IdGenerationIdentity idGenerationIdentity = new IdGenerationIdentity();
#Column(name="POLICY_ID", unique = true, nullable = false, insertable = false, updatable = false)
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long policyId;
#Column(name="CONTEXT_CD")
#Id
private String contextCd;
#Column(name="CASE_ID")
private Long caseId;
#Column(name="EMPLYR_GRP_ID")
private Long emplyrGrpId;
.....
}
Key class as below.
#Embeddable
public class IdGenerationIdentity implements Serializable {
private static final long serialVersionUID = -849058313293035312L;
// #GeneratedValue(strategy = GenerationType.IDENTITY)
//#NotNull
//#Column(name = "POLICY_ID")
//#Id
private Long policyId;
//#NotNull
//#Column(name = "CONTEXT_CD")
private String contextCd;
public IdGenerationIdentity(Long policyId, String contextCd) {
this.policyId = policyId;
this.contextCd = contextCd;
}
public IdGenerationIdentity() {
}
public Long getPolicyId() {
return policyId;
}
public void setPolicyId(Long policyId) {
this.policyId = policyId;
}
public String getContextCd() {
return contextCd;
}
public void setContextCd(String contextCd) {
this.contextCd = contextCd;
}
}
when i try to save to the DB using spring data jpa repository
policyRepository.save(policy);
i gives me an exception as below
ERROR org.springframework.boot.web.servlet.support.ErrorPageFilter - Forwarding to error page from request [/portalCase/createCase] due to exception [Error occurred while creating a new case. Error occurred while inserting policy.Could not set field value [POST_INSERT_INDICATOR] value by reflection : [class com.hmsy.pierws.portalCase.entity.IdGenerationIdentity.policyId] setter of com.hmsy.pierws.portalCase.entity.IdGenerationIdentity.policyId; nested exception is org.hibernate.PropertyAccessException: Could not set field value [POST_INSERT_INDICATOR] value by reflection : [class com.hmsy.pierws.portalCase.entity.IdGenerationIdentity.policyId] setter of com.hmsy.pierws.portalCase.entity.IdGenerationIdentity.policyId] java.lang.Exception: Error occurred while creating a new case. Error occurred while inserting policy.Could not set field value [POST_INSERT_INDICATOR] value by reflection : [class com.hmsy.pierws.portalCase.entity.IdGenerationIdentity.policyId] setter of com.hmsy.pierws.portalCase.entity.IdGenerationIdentity.policyId; nested exception is org.hibernate.PropertyAccessException: Could not set field value [POST_INSERT_INDICATOR] value by reflection : [class com.hmsy.pierws.portalCase.entity.IdGenerationIdentity.policyId] setter of com.hmsy.pierws.portalCase.entity.IdGenerationIdentity.policyId
another approach i have tried is using EmbeddedId. i have commented the same in the entity class above. when i use the embeddedId it gives me
rowid cannot be specified as a target column in insert

Could not create query for public Spring JPA

I have two classes Employee and Asset. they have a relationship #ManyToOne.
When I try to left join tables console shows a runtime error.
Please
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'assetController' defined in file [C:\Users\User\Desktop\material-assets\target\classes\com\alsecotask\materialassets\controller\AssetController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'assetService' defined in file [C:\Users\User\Desktop\material-assets\target\classes\com\alsecotask\materialassets\service\AssetService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'assetRepository' defined in com.alsecotask.materialassets.repository.AssetRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List com.alsecotask.materialassets.repository.AssetRepository.getAssetsByEmployee()! Reason: Validation failed for query for method public abstract java.util.List com.alsecotask.materialassets.repository.AssetRepository.getAssetsByEmployee()!; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.alsecotask.materialassets.repository.AssetRepository.getAssetsByEmployee()!
AssetReposiory where I wrote my query
public interface AssetRepository extends JpaRepository<Asset, Long> {
Long countAssetByEmployee_Id(Long id);
#Query("SELECT Employee.id, Employee.firstName, sum(Asset .price), count(Asset .price)\n" +
"FROM Asset \n" +
" LEFT JOIN Employee \n" +
" ON Employee .id = Asset .employee.id group by Employee .id\n")
List<?> getAssetsByEmployee();
#Query(value = "SELECT * FROM Asset WHERE name = ?1", nativeQuery = true)
Asset findByNameQuery(String name);
}
Asset class
public class Asset {
#Id
#GeneratedValue
private Long id;
private String name;
private double price;
#ManyToOne
#JoinColumn(name = "employee_id", nullable = false)
private Employee employee;}
Employee class
public class Employee {
#Id
#SequenceGenerator(
name = "employee_sequence",
sequenceName = "employee_sequence",
allocationSize = 1
)
#GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "employee_sequence"
)
private Long id;
private String firstName;
private String lastName;
public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
]
Change the return type as List<Object[]>.
#Query(value="SELECT Employee.id, Employee.firstName, sum(Asset
.price), count(Asset .price)\n" +
"FROM Asset \n" +
" LEFT JOIN Employee \n" +
" ON Employee .id = Asset .employee.id group by
Employee.id\n", nativeQuery= true)
List<Object[]> getAssetsByEmployee();

how to create new entry in ldif file (Embeded LDAP) using spring boot

I am trying to insert user details in my LDIF file which is perfectly configured with spring boot because I am able to fetch data even I am able to use LdapTemplate.bind() method.
I have tried various codes and finally, I am able to use ldapTemplate.bind() method but it only binds my entry with LDAP tree means no entry inside ldif file and as I restart my LDAP server this entry losts.
Error:
org.springframework.ldap.InvalidNameException: Invalid name: abcdtestuser#gmail.com; nested exception is javax.naming.InvalidNameException: Invalid name: abcdtestuser#gmail.com
at org.springframework.ldap.support.LdapUtils.convertLdapException(LdapUtils.java:136)
at org.springframework.ldap.support.LdapUtils.newLdapName(LdapUtils.java:416)
at org.springframework.ldap.support.LdapNameBuilder.add(LdapNameBuilder.java:121)
at in.indg.cdac.ldap.service.LdapService.saveInLdap(LdapService.java:71)
at in.indg.cdac.ldap.service.LdapService.create(LdapService.java:57)
at in.indg.cdac.ldap.controller.LdapController.saveUserDetail(LdapController.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
Entity:
#Entry(base="ou=vikaspedia", objectClasses = {"inetOrgPerson", "person", "top"})
public class User {
#Id
private Name id;
private #Attribute(name = "mail") String uid;
private #Attribute(name = "cn") String firstName;
private #Attribute(name = "sn") String lastName;
private #Attribute(name = "userPassword") String password;
private #Attribute(name = "description") String userrole;
Create Method :
public String create(UserResponsePojo userResponsePojo) {
try {
Name dn = LdapNameBuilder
.newInstance()
.add("ou", "vikaspedia")
.add("mail", userResponsePojo.getUid())
// .add("cn", userResponsePojo.getUsername())
.build();
DirContextAdapter context = new DirContextAdapter(dn);
// Name id = LdapNameBuilder
// .newInstance()
// .add(userResponsePojo.getUid())
// .build();
context.setAttributeValues("objectclass", new String[]{"inetOrgPerson", "person", "top"});
context.setAttributeValue("cn", userResponsePojo.getUsername());
context.setAttributeValue("sn", userResponsePojo.getLastname());
context.setAttributeValue("description", userResponsePojo.getUserrole());
context.setAttributeValue("mail", userResponsePojo.getUid());
context.setAttributeValue("userPassword", digestSHA(userResponsePojo.getPassword()));
ldapTemplate.bind(context);
ldapTemplate.create(context);
Maybe, Auto-Increment of Id can resolve the problem but I don't know how can I achieve that as we do with JPA #GeneratedValue(strategy = GeneratedType.IDENTITY)
Any help will be appreciated. Thanks in advance!

org.hibernate.MappingException: No Dialect mapping for JDBC type: 1111 for postgres spring data jpa

Below are my tables i am using PostgreSQL with spring data jpa
public class Person
{
#Id
#GeneratedValue( strategy = GenerationType.IDENTITY )
#Column( name = "person_id" )
private Long personId;
private String givenName;
}
public class Address
{
#Id
#GeneratedValue( strategy = GenerationType.IDENTITY )
#Column( name = "address_id" )
private Long addressId;
#ManyToOne
#JoinColumn( name = "person_id", foreignKey = #ForeignKey( name = "fk_person_person_id" ) )
Person person;
private String Address;
}
Below is my native query
User.getAllUsersWithAddress=select to_json(p.*) AS person,to_json(a.*) AS Address from person p INNER JOIN address a ON p.person_id=a.person_id
#Query( nativeQuery = true )
List<Object[]> getAllUsersWithAddress( );
But the query is throwing exception
Caused by: org.hibernate.MappingException: No Dialect mapping for JDBC type: 1111 for postgres.
even though i added below code added
public class PostgreSQLDialect extends PostgreSQL94Dialect
{
public PostgreSQLDialect()
{
super();
this.registerColumnType( Types.JAVA_OBJECT, "json" );
}
}
correct me if anything more to be added.

java.lang.IllegalArgumentException with java persistance API

I am getting a java.lang.IllegalArgumentException similar to the link given below.To solve it I tried to change the field type from Integer to Long. But still I am getting:
Caused by: java.lang.IllegalArgumentException: Parameter value [5] was not matching type [com.buddhiedge.server.entity.StudyplanCategory]
StudyplanCategory is the entity class.
The problem is similar to the one in the below link.
Hibernate - Parameter value [2011] was not matching type [java.lang.Integer]. How to solve?
My entity Class is:
#JsonIgnoreProperties({ "studyplanCategoryList", "dropboxzipfile",
"parentCategory", "createdDate", "updatedDate" })
#JsonPropertyOrder({ "id", "name", "status", "sptTutorialsList" })
#Entity
#Table(name = "studyplan_category", catalog = "buddhiedgeserver_db", schema = "", uniqueConstraints = { #UniqueConstraint(columnNames = { "dropboxzipfile" }) })
#NamedQueries({
#NamedQuery(name = "StudyplanCategory.findSubStudyPlanById", query = "SELECT s FROM StudyplanCategory s WHERE s.parentCategory=:parentCategory order by updatedDate DESC")})
public class StudyplanCategory implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "id", nullable = false)
private Long id;
}
It seems you are passing 5 as parameter to the query. If you want to pass an ID rather than an entity, change the query to:
WHERE s.parentCategory.id=:parentCategoryId

Resources