Could not execute JDBC batch update - spring

I have a problem with a entity class. When I run my app with hibernate.hbm2ddl.auto = create, then it create all the other entity tables but not this on. Why is that? And when I create the table by myself and after that try to insert something into it, then I get this error: http://pastebin.com/m4gjxqNC
Here's my entity class:
User entity:
http://pastebin.com/YXvzFSgt
Comment entity:
http://pastebin.com/RpZEUPxN
And here's the UserDAO class
http://pastebin.com/LrTCg0GC

You seems to be using PostgreSQL. As per this document, 'User' is a PostgreSQL reserved word. Try adding a #Table("user_tb") annotation for your User entity, to force a new table name.
#Entity
#Table("user_tb")
public class User extends LightEntity implements Serializable {
//..
}

Related

Springboot Joint table from different database

I have a Springboot project with two datasource configured one for each database I'm using. Everything works, but I need to create an Entity in database one that refers to an entity from database 2. The problem is that the entity in the second database is not found.
#Entity
#Table(name = "data", catalog = "data")
public class Data implements Serializable
{
//all stuff related to data here.
#ManyToOne
private User user;
//Entity User is store in the second database
}
Is there anyway to tell spring that the entity User can be found in the second datasource?

Spring: map entity to a scheme

Im trying to create a Spring-Boot Data JPA-Application with Entities based in multiple schemes using an oracle Database.s
I have two Schemes, scheme_a and scheme_b. The DDL User for scheme_a is scheme_a, the DDL user for scheme_b is scheme_b. Both DDL user will be used by liquibase to create my initial table structure.
My application has two entities:
Entity foo is managed by my application and should be based in scheme scheme_a.
Entity bar is managed by a third party library and should be based in scheme scheme_b.
My application has a user app_user, with CRUD-rights on all tables and sequences located in scheme_a and scheme_b. This user is my DMA-user
My plan was to use Spring-Data-Jpa to connect with the database using the app-user user. This user should be able to work with all entities in scheme_a and scheme_b.
Example of Entity foo (bar has identical structure):
#Entity
#Table(name = "T_FOO")
public class FooEntity {
public FooEntity () { // no-args c-tor for hibernate
}
#Id
#Column(name = "foo_id")
#SequenceGenerator(name = "sequence_foo_id", sequenceName = "sequence_foo_id")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence_foo_id")
private long id;
#Column(name = "foo_name")
private String name;
}
Every entity has its own Repository:
public interface FooRepo extends CrudRepository<FooEntity, Long> {
...
}
My configuration:
#Configuration
#EnableJpaRepositories(basePackageClasses = {FooRepo.class, BARRepo.class})
#EntityScan(basePackageClasses = {FooEntity.class, BarEntity.class})
public class AppDBConfig {
...
}
But every time my application tries to start it is not able to locate the table T_FOO based in scheme_a.
I am not able to extend the #Table-Annotation with corresponding scheme. Does any one know a way to solve this problem? Is it possible to create something like a "scheme-table" to tell hibernate in which scheme which entity is located, like
var schemeMap = new HashMap<Class, String>();
schemeMap.put(FooEntity.class, scheme_a);
schemeMap.put(BarEntity.class, scheme_b);
Greetings from Germany!
You need to specify the schema in the #Table annotation.
#Entity
#Table(name = "T_FOO", schema = "scheme_a")
public static void FooEntity {
// ..
Since you don't seem to be allowed to change the annotation on FooEntity I see a couple of options available to you:
If you can change the annotation on BarEntity but not on FooEntity you can make the schema of FooEntity your default schema and set the schema for BarEntity in the annotation.
If you can't change either entity but have some control over the database you can create a view or synonym in your main schema that mirrors T_FOO.
You can also configure Hibernate with XML and specify the schema there.
You could decompile the class file containing FooEntity, add the required annotation and compile it again.
You probably could use ByteBuddy or a similar tool to do that at runtime during startup of your application.

Fully qualify Oracle table name in Hibernate

My Setup:
I am using Hibernate 5
with the Oracle JDBC driver oracle.jdbc.driver.OracleDriver and dialect org.hibernate.dialect.Oracle9iDialect.
My modelclasses look like this:
#Entity
#Table(name = "MyModel1", catalog = "DB1")
public class MyModel1 {...}
#Entity
#Table(name = "MyModel2", catalog = "DB2")
public class MyModel2 {...}
My Problem:
I have multiple modelclasses that are spread about different DBs on the same DBserver.
I have to use a single DB-connection to query all of my modelclasses so I connect to DB1 for querying.
Everything would be fine, if Hibernate would generate SQL queries like
select * from DB1.MyModel1;
but it does not. For some reason it makes its queries without the catalog ie.
select * from MyModel1;
which is fine for MyModel1 because I connect to DB1 but I need a fully qualified query for MyModel2 otherwise it throws an exception, because the table of MyModel2 cannot be found in DB1.
Do you know any way to trick Hibernate or JPA or the dialect into building queries with fully qualified tablenames?
With Oracle you have to use the schema attribute:
#Entity
#Table(name = "MyModel1", schema= "DB1")
public class MyModel1 {...}
#Entity
#Table(name = "MyModel2", schema= "DB2")
public class MyModel2 {...}

SpringData findAll is processing all database tables and not the one requested

I am new to SpringData and I am not getting what is happening here. I have created an Interface that extends PagingAndSortingRepository and overrided the findAll() method like this:
#Override
#Query
List<MyEntity> findAll();
I am calling this method in my service, but it is making my app to throw an exception Caused by: java.lang.StackOverflowError because that method is reading through the entire database, not only from MyEntitytable in database. Any idea?
Apparently the problem is in the configuration of EclipseLink. In persistence.xml I added this row <shared-cache-mode>NONE</shared-cache-mode> and now it works as it should.
no need to override getall() method.in your service autowired that dao or repository class and using this you can directly call the findall() method.
in the case you want to write your custom method apart from what given by spring data jpa then we use the #Query to write custom query.
No Need to Override. What i have done is i have created a repository i.e
FavoriteRepository which is extending JpaRepository and i have mentioned the
dbmodel name (Favorite)
like this JpaRepository<Favorite, Long> // Here Favorite is my model name
and Long is the type of primary key mentioned in db model Favorite as #Id
#Repository
public interface FavoriteRepository extends JpaRepository<Favorite, Long>{
}
Now you can use method findOne or findAll. As these methods are present in
Jparepository.Hope so it will help
If you want to add new method then use #Query with JpQL
#Query(value = "select f from Favorite f where f.userId=:userId ")
public List<Favorite> getFavoritesForUser(#Param("userId") String userId);

H2 JdbcSQLException: "Table not found" with camelcase table & entity name

Using Spring Boot, with Spring Data JPA and H2 in-memory database (in PostgreSQL mode if it makes a difference).
I have a table & entity class named ContentBlock, yet H2 is complaining about missing CONTENT_BLOCK table, when I do a findAll() or findOne():
org.h2.jdbc.JdbcSQLException: Table "CONTENT_BLOCK" not found
I'm not sure if uppercase/camelcase makes a difference, but where does the underscore in CONTENT_BLOCK come from?
In my schema definition:
CREATE TABLE ContentBlock (
id BIGSERIAL PRIMARY KEY,
content TEXT
-- etc
);
And in the entity class:
#Entity
#Table(name = "ContentBlock")
public class ContentBlock {
// ...
}
(Of course I first tried without #Table annotation, as the class name exactly matches the table name.)
With my other tables/entities, with names like Asset, there are no problems, and I don't need to explicitly specify the table name on Java side:
#Entity
public class Asset {
// ...
}
In my setup, the H2 datasource is explicitly defined like this:
#Bean
public DataSource devDataSource() {
return new EmbeddedDatabaseBuilder()
.generateUniqueName(true)
.setType(EmbeddedDatabaseType.H2)
.setScriptEncoding("UTF-8")
.ignoreFailedDrops(true)
.addScripts("database/init.sql", "database/schema.sql", "database/test_data.sql")
.build();
}
(Contents of init.sql is SET MODE PostgreSQL;)
As workaround, I just renamed the ContentBlock table to Block in schema.sql, with #Table(name = "Block") in the Java class which I still call ContentBlock.
But this is weird, surely you can map a table with camelcase name to an entity somehow?
By default Spring Boot uses SpringNamingStrategy. It extends org.hibernate.cfg.ImprovedNamingStrategy from Hibernate 4. ImprovedNamingStrategy generates underscores in table names.
To map a table with camel case name to an entity you can use org.hibernate.cfg.EJB3NamingStrategy or implement your own.
An example of set a name strategy using properties
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy

Resources