data.sql not executing at startup in Springboot project - postgresql

Trying out with below combination but not working. Interestingly when I change the table name to an invalid one , it does flag the error during startup but with all correct nomenclature in place , it doesnt give any error and nor load the data
data.sql
INSERT INTO parameter (id,created_at, created_by,modified_at,parameter_name) VALUES (0,NULL, 2,NULL,'abcd')
application.properties
spring.datasource.url=jdbc:postgresql://localhost:5432/users
spring.datasource.username=postgres
spring.datasource.password=admin
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.format_sql=true
spring.sql.init.mode=always
Parameter.java
#Getter
#Setter
#EqualsAndHashCode
#NoArgsConstructor
#Entity
public class Parameter {
#Id
#SequenceGenerator(
name = "parameter_sequence",
sequenceName = "parameter_sequence",
allocationSize = 1
)
#GeneratedValue(
strategy = GenerationType.IDENTITY,
generator = "parameter_sequence"
)
private Long id;
private String parameterName;
.....
tried various combinations but not working

Related

Spring Data Jpa how to select all columns by using CriteriaQuery

In the following code, if I used query.multiselect(generalVecEntityRoot) to query all columns in entity, it throws exception, Unable to locate appropriate constructor as in
org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate appropriate constructor on class [general.GeneralVecEntity]. Expected arguments are: general.GeneralVecEntity [select new general.GeneralVecEntity(generatedAlias0) from general.GeneralVecEntity as generatedAlias0 where ( generatedAlias0.groupId in (:param0) ) and ( generatedAlias0.appId=:param1 )]
However, instead, listing columns one by one would work, but code could be tedious and hard to read, so I would like to use Root object to query all columns, but no idea what was wrong. The following are query function and entity definition. Thanks.
private List<GeneralVecEntity> findGeneralVecByGroupIdInAndAppIdGroupingByGroupId(String appId, String[] groupIds) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<GeneralVecEntity> query = cb.createQuery(GeneralVecEntity.class);
Root<GeneralVecEntity> generalVecEntityRoot = query.from(GeneralVecEntity.class);
query.where(generalVecEntityRoot.get("groupId").in(groupIds), cb.equal(generalVecEntityRoot.get("appId"), appId));
CriteriaQuery<GeneralVecEntity> cq = query.multiselect(generalVecEntityRoot.get("id"),
generalVecEntityRoot.get("groupId"),
generalVecEntityRoot.get("appId"),
generalVecEntityRoot.get("vec"),
generalVecEntityRoot.get("createTime"));
return em.createQuery(cq).getResultList();
}
#Entity
#Getter
#Setter
#ToString
#Table(name = "general_vec")
#AllArgsConstructor
#NoArgsConstructor
public class GeneralVecEntity {
#Id
#GeneratedValue
private Long id;
private String groupId;
private String appId;
#Lob
#Column(name="vec", columnDefinition="TEXT NOT NULL")
#Convert(converter= DbConverter.ListToJson.class)
private float[] vec;
#Column(name="create_time",columnDefinition="timestamp", updatable = false)
#CreationTimestamp
private LocalDateTime createTime;
}

Cannot access Postgres database with Hibernate

I was already searching for a solution but I cannot find any.
My problem is that I cannot my Postgres database, called IncomeOutgo, via Hibernate.
I always get this error message when calling my Thymeleaf/HTML website.
So does my application.properties look like
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=none
spring.jpa.hibernate.show-sql=true
spring.datasource.url=jdbc:postgresql://192.168.0.227:5432/IncomeOutgo
spring.datasource.username=postgres
spring.datasource.password=XXX
#spring.jpa.properties.hibernate.format_sql=true
So does my table look like in Postgres (DBeaver):
And last but not least so does my Domain/Entity look like:
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
#Entity
#Table
public class IncomeOutgo extends AbstractPersistable<Long> {
#Version
#Column(name ="id")
private Long id;
#Column(name="dayofweek")
private Date dayofweek;
#Size(min = 5, max = 50)
#Column(name ="person")
private String person;
#Min(0)
#Column(name ="version")
private Integer version;
#Column(name="income")
private int income;
#Column(name="outgo")
private int outgo;
}
Maybe, someone can tell me what my error is?
Thanks in advance!
I was able to make it work now.
LesiakĀ“s hint with the schema name made me do a workaround.
I created a new database: incomeoutgo (lower letter case), and under schema: public, a new table: incomeoutgo with lower letters, too.
And so does my Domain definition look like:
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
#Entity
#Table(name="incomeoutgo", schema = "public")
public class IncomeOutgo extends AbstractPersistable<Long> {
#Version
#NotNull
#Column(name ="id")
private Long id;
#Column(name="dayofweek")
private Date dayofweek;
#Size(min = 5, max = 50)
#Column(name ="person")
private String person;
#Min(0)
#Column(name ="version")
private Integer version;
#Column(name="income")
private int income;
#Column(name="outgo")
private int outgo;
}

Hibernate ignores the schema name while calling nextval() - from postgres 12

My pojo definition worked fine till I used Postgres 9.x, When I changed the database to postgres 12 I get Sequence not found error when inserting a new row to a table. When I debugged the sql statements run in the database I found that hibernate ignored the schema name.
Postgres 9 : select nextval('ita.ita_settings_is_is_id_seq')....
Postgres 12: select nextval('ita_settings_is_is_id_seq')....
My Pojo definition is as follows
#Entity
#Table(name = "ita.ita_settings_is")
#SequenceGenerator(name = "settingItaIdSeq", sequenceName = "ita.ita_settings_is_is_id_seq", initialValue = 1, allocationSize = 1)
public class itaSettings implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "settingitaIdSeq")
#Column(name = "is_id")
private int id;

JPA Spring Boot postgresql : Insert data with the last ID

I have a MyClass entity with an auto increment id at the time of the project deployment I have an init.sql file to initialize the MY_CLASS table by adding two lines
the problem when I use my web service REST to insert a new line in the MY_CLASS table I have an error message of duplicate key of id 1 for the first click and id 2 on the second click but after the POST goes without problems. To solve this problem I can add the following line in my init.sql file
ALTER SEQUENCE MY_CLASS_id_seq RESTART WITH 3;
My question: How can I configure my POST to persist the data with the last id because whenever I can insert data with SQL.
#Entity
#Cacheable
#Getter
#Setter
#Table(name = "MY_CLASS")
public class MyClass {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
private String label;
}
#RepositoryRestResource(collectionResourceRel = "clazz", path = "clazz")
public interface MyClassRepository extends PagingAndSortingRepository<MyClass, Long> {
}
init.sql
INSERT INTO public.MY_CLASS (label) values('label_1');
INSERT INTO public.MY_CLASS (label) values('label_2');
Wouldn't you use the sequence generator, would you?
public class MyClass {
public static final String SEQUENCE_NAME = "MY_CLASS_id_seq";
#Id
#GeneratedValue(strategy = SEQUENCE, generator = SEQUENCE_NAME)
#SequenceGenerator(name = SEQUENCE_NAME, sequenceName = SEQUENCE_NAME)
private Long id;
#NotNull
private String label;
}

JPA transaction/rollback behaviour with objects persisted via cascade

I have two objects Antrag (application) and Anlage (facility). An application can be made for multiple facilities. The application is persisted directly in the DAO. The facilities are persisted via cascade.
#Entity
#Table(name = "EEG_ANTRAG")
public class Antrag implements Serializable {
private static final long serialVersionUID = -2440344011443487714L;
#Id
#Column(name = "ANT_ID", nullable = false)
#SequenceGenerator(name = "sequenceGeneratorAntrag", sequenceName = "EEG_ANTRAG_SEQ", allocationSize = 1)
#GeneratedValue(generator = "sequenceGeneratorAntrag")
#Getter #Setter private Long id;
#OneToMany(mappedBy = "antrag", cascade = { CascadeType.ALL }, orphanRemoval = true)
#OrderBy("id ASC")
#Getter private List<Anlage> anlageList = new ArrayList<Anlage>();
public Anlage addAnlage(Anlage anlage)
anlageList.add(anlage);
anlage.setApplication(this);
return anlage;
}
/* some more simple attributes; just Strings, boolean, .. */
}
#Entity
#Table(name = "EEG_ANLAGE")
public class Anlage implements Serializable {
private static final long serialVersionUID = -3940344011443487741L;
#Id
#Column(name = "ANL_ID")
#SequenceGenerator(name = "sequenceGeneratorAnlage", sequenceName = "EEG_ANLAGE_SEQ", allocationSize = 1)
#GeneratedValue(generator = "sequenceGeneratorAnlage")
#Getter #Setter private Long id;
#ManyToOne
#JoinColumn(name = "ANL_ANT_ID")
#Getter #Setter private Antrag antrag;
/* some more simple attributes; just Strings, boolean, .. */
}
#Stateless
public class AntragDaoBean implements AntragDaoLocal {
#PersistenceContext(unitName = "ejb-model")
private EntityManager em;
#Override
public void persistAntrag(Antrag antrag) {
em.persist(antrag);
}
}
When an error occurs on inserting the facilities, e.g. some column name is misspelled in the entity, an exception is thrown. The stacktrace indicates, that a rollback was performed. The problem is, that the application is still persisted. Shouldn't the insertion of the application be rolled back as well?
We are using EclipseLink 2.4.1. The EclipseLink debug output states, that all inserts are performed in one single transaction. The database is Oracle 11g.
Is my ecpectation of the transactional behaviour wrong? How do I get the behaviour I want?
/* shortened exemplary stacktrace for rollback */
EvaluationException:
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
EJBTransactionRolledbackException:
org.jboss.as.ejb3.tx.CMTTxInterceptor.handleEndTransactionException(CMTTxInterceptor.java:115)
RollbackException:
com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.commitAndDisassociate(TransactionImple.java:1177)
DatabaseException:
org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
SQLSyntaxErrorException:
oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:445)
Your expectation is correct: everything should be made in a single transaction, and the insertion of Antrag should be rolled back as well.
I think your persistence-unit is simply not JTA: test in the persistence.xml file that you have something like:
<persistence-unit name="ejb-model" transaction-type="JTA">
<jta-data-source>java:/someNameDB</jta-data-source>