hibernate.hbm2ddl.auto with auto does not add new column - java

After I add #Embedded with BigDecimals:
#Embeddable
public class ChildGrossNetTransformVariables {
#Column(name = "amount", precision = 19, scale = 4)
public BigDecimal amount;
...
Usage in another entities:
#Embedded
protected ParentGrossNetTransformVariables grossNetTransform;
lConf.setProperty("hibernate.hbm2ddl.auto", "auto") stoped working (I need argument "auto" but I checked also lConf.setProperty("hibernate.hbm2ddl.auto", "create-drop") and with "create-drop" argument the database was created properly). When I try to add new column to check if column autoupdate works:
#Type(type="java.lang.String")
#Column(name = "test")
protected String test;
The error
SQLGrammarException: could not extract ResultSet
...
org.postgresql.util.PSQLException: Error: the Column this._test doesnt exist
Can i debug it somehow?
I tried lConf.setProperty("hibernate.show_sql", "true"); but the first log is SELECT ... statement instead of ALTER TABLE

auto is not valid value for hibernate.hbm2ddl.auto you really mean update. Try again.

Related

only select columns of the a psql table could receive data

Something very bizarre have been happening. I have a very simple Entity recipe like so
#Data
#Entity
#Table(name = "recipe", schema = "public")
#AllArgsConstructor
#NoArgsConstructor
public class Recipe {
#Id
#GeneratedValue(
strategy = GenerationType.IDENTITY
)
#Column(name = "id", updatable = false, nullable = false)
private long id;
#Column(name = "name")
private String name;
#Column(name = "instructions")
private String instructions;
#Column(name = "date_added", nullable = false)
private String dateAdded;
#Column(name = "last_edited", nullable = false)
private String lastEdited;
}
and I have this post service that should post the 4 string attribute to the database
public void postRecipe(Recipe recipe){
var sql = """
INSERT INTO public.recipe ("name","instructions","date_added","last_edited")
VALUES (?, ?, ?, ?)
""";
jdbcTemplate.update(
sql,
recipe.getName(),
recipe.getInstructions(),
recipe.getDateAdded(),
recipe.getLastEdited()
);
}
However when the following jason is sent using postman, I get the null value error.
{
"name":"test",
"instructions":"don't eat",
"date_added":"03/04/2017",
"last_edited":"03/04/2017"
}
ERROR: null value in column \"date_added\" of relation \"recipe\" violates not-null constraint\n Detail: Failing row contains (3, null, don't eat, null, test)
The strangest thing is that only the "name" and "instruction" columns receive their data and not the other columns. I have tried adding another String attribute to the Entity class and it also cannot get data from the jason.
Edit 1:
I have tried adding the data directly through pgadmin and it worked fine
INSERT INTO recipe (name, instructions, date_added, last_edited)
VALUES ('test', 'test instruction', '2020/03/05', '2020/05/08');
It looks like your deserialization is broken - transforming your JSON into the Java entity, which results in some null values present. Most likely because date_added != dateAdded (field name), and Jackson cannot properly set a value.
I recommend having a look at Jackson guide: https://www.baeldung.com/jackson-annotations, #JsonProperty specifically. And overall do not mix entities and DTOs
After many trials and errors I was able to come up with a solution but still have no clue as to why this is happening. It turns out the under score in the annotation is the problem.
//won't work
#Column(name = date_added)
//works
#Column(name = dateadded)
This is pretty strange because I am fairly certain that the under score is generated by hibernate.
if anyone know why this is happening please let me know... for now I will just stay away from the under scrolls.

Quarkus with hibernate found [bpchar (Types#CHAR)], but expecting [char (Types#VARCHAR)]

Hello i'm trying to learn Quarkus with Hibernate but i've ran into an issue the schema-validation.
The error:
2021-12-29 16:05:14,915 ERROR
[io.qua.hib.orm.run.sch.SchemaManagementIntegrator] (Hibernate
post-boot validation thread for ) Failed to validate Schema:
Schema-validation: wrong column type encount ered in column [BED_INFO]
in table [ROOM]; found [bpchar (Types#CHAR)], but expecting [char
(Types#VARCHAR)] 2021-12-29 16:05:14,921 ERROR
[io.qua.hib.orm.run.sch.SchemaManagementIntegrator] (Hibernate
post-boot validation thread for ) The following SQL may
resolve the database issues, as generated by the Hibernate schema
migration tool. WARNING: You must manually verify this SQL is correct,
this is a best effort guess, do not copy/paste it without verifying
that it does what you expect.
the class Room looks like this
#Entity
#Table(name = "ROOM")
public class Room {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ROOM_ID")
private long id;
#Column(name = "NAME")
private String name;
#Column(name = "ROOM_NUMBER")
private String roomNumber;
#Column(name = "BED_INFO", columnDefinition = "char")
private String bedInfo;
public Room(String name, String roomNumber, String bedInfo) {
this.name = name;
this.roomNumber = roomNumber;
this.bedInfo = bedInfo;
}
}
and the mysql schema like this
CREATE TABLE ROOM(
ROOM_ID BIGSERIAL PRIMARY KEY,
NAME VARCHAR(16) NOT NULL,
ROOM_NUMBER CHAR(2) NOT NULL UNIQUE,
BED_INFO CHAR(2) NOT NULL
);
According to their documentation this "should" work but i'm perhaps missing something here.
[BED_INFO] in table [ROOM]; found [bpchar (Types#CHAR)], but expecting [char (Types#VARCHAR)]
Means that Hibernate has found a bpchar(char) where it would expect a varchar. It seems that columnDefinition does not handle char. If you really want it to be a char, try bpchar instead.
In case it doesn't work, try running your quarkus app in dev mode with this option in the application.properties file.
quarkus.hibernate-orm.database.generation=create
This will generate the actual DDL for your database that Hibernate is expecting.
Personally I would refrain from columnDefinition, instead i would use length and nullable. Unless you are building an app on an existent, I would also remove name and #Table.

Customizing Spring Data queries

I have 'iddId'(primary key) column and 'idd_id'(unused column) in the table. When I trying to execute
'findAll' method via Spring Data JPA I get empty 'iddId' field in created object because the hibernate query looks like:
select 'idd0_.idd_id as col_0_0_'...
I tried to map fields manually with a #Column(name = "iddId") annotation but nothing was changed. Then I tryed to add an additional field to the entity 'idd_id' which is annotated with #Column(name="idd_id) and received the exception:
'org.hibernate.DuplicateMappingException: Table [idd] contains physical column name [idd_id] referred to by multiple logical column names: [idd_id], [iddId]'.
Is it possible to make a query like that: 'select idd0_.iddId as col_0_0_'?
public class Idd {
#Id
#Column(name = "iddId")
private String iddId;
#Column(name = "idd_id")
private String idd_id;
}
MySql: 5.7.28
Spring Data: 2.2.2
Just add:
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
to application.properties

Cannot resolve column [name] in Java using Microsoft SQL Server and Javax.Persistence

One of my classes that convert table in SQL Server database to entities.
#Id
#Column(name = "[primary_key]")
private int id;
#Column(name = "[id Employee]")
private byte[] employeeId;
#Column(name = "[Period]")
private Date period;
#Column(name = "[Credit amount]")
private float creditAmount;
#Column(name = "[Type]")
private String type;
#Column(name = "[Weight 585]")
private float weight585;
and CrudRepo for it (partial):
#Query(value = "select sum([Weight 585]) from [ZOK per period] where ([Period] between ?1 and ?2) " +
"and ([id Employee] = ?3) and ([Type] = 'Gold')", nativeQuery = true)
Double getSumZokGold(Date start, Date end, byte[] employeeId);
All my column names are red and underlined with two errors:
Cannot resolve column '';
Unknown database function '';
I checked persistence and data already assigned - its most popular solution of this problem. I checked dialect - SQL Server, already. I checked ALL column names and didn't see any mistake.
To solve this problem you may do:
Check all columns names - yes, problem can be just in it. By the way, you will have an Error if its true.
Add new Database in Database (right IDE side) and connect to your data source.
Check your Persistence (bottom left corner in "Intellij IDEa"), press Assign Data... and use in Data Source not default source, but exactly yours.
If you have already connected database (MS Server, for example) - reconnect. Yes, its useful too.
Now, if your problem still annoying you - open File - Invalidate Caches / Restart and choose blue button Invalidate and Restart.
P.S.: If you use russian names for your table columns in database - write them as #Column(name = "[...]") and in SQL #Query put N before value in "" or write name in brackets. But the best idea - use just English!

Automatically Insert first row soon after table is created / recreated using Hibernate

I want Username = Administrator and Password = admin, soon after table is created (or whenever table is recreate).
Is there any way to insert first row using following code. I do not want to use a separate insert query
Is there any constraint in Hibernate to restrict user from deleting (first) row
#Entity
#Table(name = "Users")
public class Users implements Serializable {
#Id
#Column(name = "Username", unique = true, nullable = false)
private String username;
#Column(name = "Password", nullable = false)
private String password;
/**************** getter & setter ************/
}
What you seem to be looking for is called fixtures. With Hibernate you can supply import.sql file on your classpath with your initial data (insert statements).
There's a bit more information on the JBoss' site.
The import.sql file is a simple text file with SQL statements, one line per statement:
insert into users (id, username) values (1, 'administrator');
insert into users (id, username) values (2, 'user');
...

Categories

Resources