Spring boot test throws JdbcException "table not found" - java

I have application-test.properties where I defined two datasources
app.datasource.server.url=jdbc:h2:mem:fooserver
app.datasource.server.username=sa
app.datasource.server.password=
app.datasource.server.driverClassName=org.h2.Driver
app.datasource.server.hikari.minimumIdle=5
app.datasource.server.hikari.maximumPoolSize=50
app.datasource.server.hikari.idleTimeout=50000
app.datasource.server.hikari.maxLifetime=55000
app.datasource.manager.url=jdbc:h2:mem:barmanager
app.datasource.manager.username=sa
app.datasource.manager.password=
app.datasource.manager.driverClassName=org.h2.Driver
app.datasource.manager.hikari.minimumIdle=5
app.datasource.manager.hikari.maximumPoolSize=50
app.datasource.manager.hikari.idleTimeout=50000
app.datasource.manager.hikari.maxLifetime=55000
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto=create-drop
#logging
logging.level.root=info
logging.file=foobar-rest-test.log
#required for SpringBootTest does not know why
spring.main.allow-bean-definition-overriding=true
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
Each of the datasource requires schema to be available named "foo" this will be created by a schema-fooserver.sql and schema-barmanager.sql in each of these sql scripts the foo schema will be created. Therefore I defined a dataSourceIntializer Bean where I can define which schema-sql file will be loaded.
#Bean(name = "managerDataSourceInitializer")
public DataSourceInitializer dataSourceInitializer1(#Qualifier("managerDataSource") DataSource datasource) {
ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
resourceDatabasePopulator.addScript(new ClassPathResource("schema-barmanager.sql"));
DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
dataSourceInitializer.setDataSource(datasource);
dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);
return dataSourceInitializer;
}
#Bean(name = "serverDataSourceInitializer")
public DataSourceInitializer dataSourceInitializer1(#Qualifier("serverDataSource") DataSource datasource) {
ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
resourceDatabasePopulator.addScript(new ClassPathResource("schema-fooserver.sql"));
DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
dataSourceInitializer.setDataSource(datasource);
dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);
return dataSourceInitializer;
}
During the start of my test the logs show that these schema files have been called and executed.
2019-03-28 15:04:34.252 DEBUG 3124 --- [main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [schema-fooserver.sql]
2019-03-28 15:04:34.252 DEBUG 3124 --- [main] o.s.jdbc.datasource.init.ScriptUtils : 0 returned as update count for SQL: CREATE SCHEMA IF NOT EXISTS FOO
2019-03-28 15:04:34.252 DEBUG 3124 --- [main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [schema-fooserver.sql] in 0 ms.
2019-03-28 15:04:34.252 DEBUG 3124 --- [main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [schema-barserver.sql]
2019-03-28 15:04:34.252 DEBUG 3124 --- [main] o.s.jdbc.datasource.init.ScriptUtils : 0 returned as update count for SQL: CREATE SCHEMA IF NOT EXISTS FOO
2019-03-28 15:04:34.252 DEBUG 3124 --- [main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [schema-barserver.sql] in 0 ms.
Now when I try to execute my test case it fails because of the following error:
28 15:04:36.035 DEBUG 3124 --- [ main] org.hibernate.SQL : insert into foo.Account (uid, password_hash, login) values (null, ?, ?)
Hibernate: insert into foo.Account (uid, password_hash, login) values (null, ?, ?)
2019-03-28 15:04:36.036 DEBUG 3124 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : could not prepare statement [insert into foo.Account (uid, password_hash, login) values (null, ?, ?)]
org.h2.jdbc.JdbcSQLException: Tabelle "ACCOUNT" nicht gefunden
Table "ACCOUNT" not found; SQL statement:
insert into foo.Account (uid, password_hash, login) values (null, ?, ?) [42102-197]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
At this point I am trying to create a UserAccount in my testcase
This is the defined UerEntity
#AllArgsConstructor
#NoArgsConstructor
#Data
#Entity
#Table(name = "foo.Account")
public class UserEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "uid")
private Long id;
#Column(name = "login")
private String username;
#Column(name = "password_hash")
private String password;
....
Here is the Testcase. The error occurs when the before mehod is called during the createUser Method.
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#ActiveProfiles("test")
#AutoConfigureMockMvc
public class UserControllerTest {
private static final Logger LOG = LoggerFactory.getLogger(UserControllerTest.class);
#LocalServerPort
private int port;
TestRestTemplate restTemplate = new TestRestTemplate();
HttpHeaders headers = new HttpHeaders();
#Autowired
private WfcSpringRestApplication controller;
#Autowired
private UserRepository repository;
#Autowired
private MockMvc mvc;
private AuthenticationToken authToken;
#Before
public void before() throws Exception {
headers = new HttpHeaders();
UserEntity user = createTestUser(TEST_ADMIN_USER, TEST_ADMIN_MD5_PW, UserRight.ADMIN);
UserEntity userService = createTestUser(TEST_SERVICE_USER, TEST_ADMIN_MD5_PW, UserRight.SERVICE);
getAuthenticationTokenForTestUser(user);
}
private UserEntity createTestUser(String username, String md5_password, UserRight right) {
UserEntity ue = new UserEntity();
ue.setUsername(username);
ue.setPassword(md5_password);
UserRole roleAdmin = new UserRole();
roleAdmin.setRight(right);
ue.getRoles().put(roleAdmin.getRight(), roleAdmin);
repository.save(ue);
return ue;
}
#Test
public void contextLoads() {
assertThat(controller).isNotNull();
}
In the error message there is the correct table name "could not prepare statement [insert into foo.Account" why it throws the exception that the table account is not found?

I faced similar error and I tried pretty much every solution mentioned on other websites such as DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1; DB_CLOSE_ON_EXIT=FALSE; IGNORECASE=TRUE
But nothing worked for me.
For Spring Boot 2.4+ use spring.jpa.defer-datasource-initialization=true in application.properties (mentioned here - https://stackoverflow.com/a/68086707/8219358)
Another way that worked for me was renaming data.sql to import.sql
I found it here - https://stackoverflow.com/a/53179547/8219358
I realize other solutions are more logical but none of them worked for me and this did.

Related

Querying with ManyToOne association results in SQLException

I am trying out a simple use case for many-to-one association with Spring Data JPA but it is resulting in an SQLException.
Model is of typical Order and OrderItem classes.
Order
#Entity
public class Order {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
OrderItem
#Entity
public class OrderItem {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
#ManyToOne
#JoinColumn(name = "fk_order")
private Order order;
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
}
Unit test
#SpringBootTest
public class MappingTests {
#Autowired
private OrderRepository orderRepository;
#Autowired
private OrderItemRepository orderItemRepository;
#Test
#Transactional
#Disabled
public void testManyToOneUnidirectional() {
Order order = new Order();
order.setName("order-01");
orderRepository.save(order);
OrderItem orderItem = new OrderItem();
orderItem.setName("item-01");
orderItem.setOrder(order);
orderItemRepository.save(orderItem);
// List<OrderItem> all = orderItemRepository.findAll();
}
Unit test passes. But if I uncomment the line to find all items from OrderItemRepository it fails with following exception:
2020-11-17 11:37:07.671 WARN 35823 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 42001, SQLState: 42001
2020-11-17 11:37:07.671 ERROR 35823 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Syntax error in SQL statement "INSERT INTO ORDER[*] (NAME, ID) VALUES (?, ?)"; expected "identifier"; SQL statement:
insert into order (name, id) values (?, ?) [42001-200]
2020-11-17 11:37:07.685 INFO 35823 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test: [DefaultTestContext#6c61a903 testClass = MappingTests, testInstance = com.example.jpademo.MappingTests#5408d4b3, testMethod = testManyToOneUnidirectional#MappingTests, testException = org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [insert into order (name, id) values (?, ?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement, mergedContextConfiguration = [WebMergedContextConfiguration#658c5a19 testClass = MappingTests, locations = '{}', classes = '{class com.example.jpademo.JpaDemoApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer#66d18979, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer#17f7cd29, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer#0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer#7ee8290b, org.springframework.boot.test.web.reactive.server.WebTestClientContextCustomizer#2e377400, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer#e4487af, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer#0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer#683dbc2c, org.springframework.boot.test.context.SpringBootTestArgs#1, org.springframework.boot.test.context.SpringBootTestWebEnvironment#233c0b17], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true]]
org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [insert into order (name, id) values (?, ?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:259)
What could be missing here ?
Thanks.
While schema is created by hibernate, it seems to fail with following error if comes across table named 'order'. I renamed the table to some other name and it worked as expected. I think hibernate identifies order as keyword rather than entity name.
2020-11-17 16:14:51.097 WARN 126490 --- [ task-1] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL "drop table if exists order CASCADE " via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "drop table if exists order CASCADE " via JDBC Statement
I had this same issue a while back.
Hibernate is trying to execute "drop table if exists order CASCADE " but ORDER is a keyword, and your table name is also ORDER. If you can add #Entity(name = "Orders") to your order entity. Your error should get fixed.

Why Spring boot JPA native update is giving PSQLException with postgres Database?

I have this Entity class:
#Entity
#Table(name = "inbox_inbox")
#Getter
#Setter
#TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
public class Inbox implements Serializable {
#Id
private int id;
#Column(name = "created")
private Date created;
#Column(name = "modified")
private Date modified;
#Column(name = "status")
private String status;
}
I have this repository:
#Repository
public interface InboxRepository extends JpaRepository<Inbox, Integer> {
List<Inbox> findInboxesByStatus(String status);
#Modifying
#Transactional
#Query(value = "update inbox_inbox i set i.status = ?2 where i.id = ?1", nativeQuery = true)
int setInboxStatusById(int id, String status);
}
If I call findInboxesByStatus(String status) with required status, then it gives the expected result. But when calling setInboxStatusById() then it is giving me an exception!
I am giving my calling part here:
int updatedRows = inboxRepository.setInboxStatusById(2, "processing");
And getting this exception:
2020-02-10 22:21:57.486 DEBUG 7 --- [main] o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [org.springframework.data.jpa.repository.support.SimpleJpaRepository.setInboxStatusById]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
2020-02-10 22:21:57.486 DEBUG 7 --- [main] o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(1663686815<open>)] for JPA transaction
2020-02-10 22:21:57.486 DEBUG 7 --- [main] o.h.e.t.internal.TransactionImpl : On TransactionImpl creation, JpaCompliance#isJpaTransactionComplianceEnabled == false
2020-02-10 22:21:57.486 DEBUG 7 --- [main] o.h.e.t.internal.TransactionImpl : begin
2020-02-10 22:21:57.486 DEBUG 7 --- [main] org.postgresql.jdbc.PgConnection : setAutoCommit = false
2020-02-10 22:21:57.486 DEBUG 7 --- [main] o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle#10fc01e0]
2020-02-10 22:21:57.487 DEBUG 7 --- [main] org.hibernate.SQL : update inbox_inbox i set i.status = ? where i.id = ?
2020-02-10 22:21:57.487 DEBUG 7 --- [main] o.h.engine.jdbc.spi.SqlExceptionHelper : could not execute statement [n/a]
org.postgresql.util.PSQLException: ERROR: column "i" of relation "inbox_inbox" does not exist
Position: 26
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2497) ~[postgresql-42.2.8.jar!/:42.2.8]
at .....
Why getting this? I searched for some solution in this site as well. But it seems, it is a new thread. So asking for help. Thanks in advance.
Using aliases in the update query is not allowed. Please, use the following:
#Modifying
#Transactional
#Query(value = "update inbox_inbox set status = ?2 where id = ?1", nativeQuery = true)
int setInboxStatusById(int id, String status);

Hibernate - Mapping three tables with a single save

I am trying to create a project that will use Hibernate to store the objects to the database.
If I simply insert (save) an object that does not contain a mapping with another table everything works fine. However, I have a case where there is a connection between three tables. The tables are the Asset, MonetaryValue and CurrencyType (see below).
When an Asset is inserted, the monetaryValueType must be provided (by the user ) along with the currency type. Asset holds a OneToOne relation with the MonetaryValueType and MonetaryValueType holds a OneToOne relation to the CurrencyType Table.
More specifically, below you will find the database tables.
Asset(asset_id,ownerIID,valueID,samID), where valueID is the foreign key to the MonetaryValueType Table (OneToOne undirectional mapping)
MonetaryValueType(mvID, mValue,currencyId), where currencyID is the foreign key to the CurrencyType Table (OneToOne undirectional mapping)
CurrencyType(currencyID,currField,currValue,currSymbol).
The problem is that every time I create the asset object and I am calling the asset service to save the element, Hibernate either create a select query that tries to select from a database table I did never define or Inserts in the currency field with wrong column names (i.e. currency_field instead of currField etc.)
I've tried to play with all the Cascade types but nothing seems to work.
Asset.java
#Entity
#Table(name="asset")
public class Asset implements java.io.Serializable{
#Id
#Column(name="assetID", unique = true, nullable = false)
private long assetID;
#Column(name="ownerID")
private long ownerID;
#OneToOne
#JoinColumn(name="valueID")
private MonetaryValueType monetaryValueType;
#Column(name="samID")
private long samID;
------------Constructor, Getters , Setters-----
MonetaryValueType.java
#Entity
#Table(name="monetaryvaluetype")
public class MonetaryValueType{
#Id
#Column(name="mvID",nullable = false,unique = true)
private Long id;
#Column(name="mValue")
private double mValue;
#OneToOne
#JoinColumn(name="currencyId")
private CurrencyType currency;
------------Constructor, Getters , Setters-----
CurrencyType.java
#Entity
#Table(name="currencytype")
public class CurrencyType implements java.io.Serializable {
#Id
#Column(name="currencyID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int currencyID;
#Column(name="currField")
private String currField;
#Column(name="currValue")
private String currValue;
#Column(name="currSymbol")
private String currSymbol;
------------Constructor, Getters , Setters-----
Every entity holds its own DAO,DAOImpl, Service and ServiceImpl class. For instance, for the asset class the DAOImpl and ServiceImpl can be found below:
AssetDAOImpl.java
#Repository
public class AssetDAOImpl implements AssetDAO{
private Logger logger = LoggerFactory.getLogger(this.getClass());
//entity manager field
#Autowired
private EntityManager entityManager;
#Override
public List<Asset> findAll() {
Session currentSession = entityManager.unwrap(Session.class);
//create a query
Query theQuery =
currentSession.createQuery("from asset",Asset.class);
//execute query and get result list
List<Asset> aModelElements = theQuery.getResultList();
//return the results
return aModelElements;
}
#Override
public Asset findById(int theId) {
return null;
}
#Override
public Asset insert(Asset assetElement) {
//Session currentSession = entityManager.unwrap(Session.class);
boolean success = false;
try {
entityManager.persist(assetElement);
logger.info("Asset -> {}", assetElement);
return assetElement;
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
AssetServiceImpl.java
#Service
public class AssetServiceImpl implements AssetService {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private AssetDAO assetDAO;
#Autowired
public AssetServiceImpl(AssetDAO theAssetDAO){
assetDAO=theAssetDAO;
}
#Override
#Transactional
public List<Asset> findAll() {
return assetDAO.findAll();
}
#Override
#Transactional
public Asset findById(int theId) {
return assetDAO.findById(theId);
}
#Override
#Transactional
public Asset insert(Asset theAsset) {
assetDAO.insert(theAsset);
return theAsset;
}
...
The class that I use to fill the asset class (and all its children) is:
UniqueIDGenerator uniqueIDGenerator = new UniqueIDGenerator();
CurrencyType currencyType = new CurrencyType();
Asset asset = new Asset();
MonetaryValueType monetaryValueType = new MonetaryValueType();
currencyType.setCurrValue(ctx.value().monetaryValueType().currency().CurrencyType().getText());
currencyType.setCurrSymbol("currency");
monetaryValueType.setId(uniqueIDGenerator.nextId());
monetaryValueType.setmValue(Double.parseDouble(ctx.value().monetaryValueType().mValue().getText()));
monetaryValueType.setCurrency(currencyType);
asset.setMonetaryValueType(monetaryValueType);
asset.setAssetID(uniqueIDGenerator.nextId());
asset.setOwner(uniqueIDGenerator.nextId());
asset.setSamID(uniqueIDGenerator.nextId());
assetService.insert(asset);
Whenever I call the class mentioned above, I get the following error:
Hibernate:
insert
into
element1
(datefrom, dateto, description, name, statusid, samid)
values
(?, ?, ?, ?, ?, ?)
2019-08-05 20:19:00 INFO MyClass:63 - the result is:true
Hibernate:
select
monetaryva_.mvid,
monetaryva_.currency_id as currency3_57_,
monetaryva_.m_value as m_value2_57_
from
monetaryvaluetype monetaryva_
where
monetaryva_.mvid=?
2019-08-05 20:19:01.084 WARN 56712 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1054, SQLState: 42S22
2019-08-05 20:19:01.084 ERROR 56712 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : Unknown column 'monetaryva_.currency_id' in 'field list'
As you can see, hibernate created columns (currency_id instead of currencyID) that are not in accordance with my database tables even though I used the #Column annotation.
Use following two lines in your application.properties file
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

Hibernate Annotation relations does not work with spring.jpa.generate-ddl=true

I am creating some simple Spring Boot project with Hibernate JPA.
I created some data model which consists 5 tables for now and created entities reflecting tables. I have set spring.jpa.generate-ddl=true and my entities was correctly reflected by schema created in PostgreSQL.
Next step was to start adding relations.
Part of my assumed datamodel is (paron my UML)
Very simple one to many relation.
My entities look that way (getters and setters omitted below, exist in code):
#Entity
public class AppUser {
#Id
#GeneratedValue
private long id;
private String name;
private String secondName;
private String email;
private java.util.Date joinDate;
#ManyToOne
#JoinColumn(name = "user_role_id")
private UserRole userRole;
}
#Entity
public class UserRole {
#Id
#GeneratedValue
private long id;
private String roleName;
}
I launch my application with spring.jpa.generate-ddl=true and column user_role_id gets created in AppUser table but application fails to start due errors:
2018-10-11 19:41:35.435 INFO 45564 --- [ main] org.hibernate.tool.hbm2ddl.SchemaUpdate : HHH000228: Running hbm2ddl schema update
2018-10-11 19:41:35.466 WARN 45564 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 42703
2018-10-11 19:41:35.466 ERROR 45564 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: column t1.tgconstrname does not exist
There is full stacktrace (please advise if should paste it here instead of pastebin:
https://pastebin.com/x4qNJkK9
When I set spring.jpa.generate-ddl=false application starts succesfully.
Any ideas why is that happening?

Hibernate: Create psql schema before the tables

I am currently developing various junit tests for hibernate. Some Hibernate model classes refer to a different schema as "public". For example, the schema "internal". Now I have to create this schema "internally" before the tables are created. How do I get this implemented with Hibernate?
Test.java
#Before
public void setUp() throws IOException, URISyntaxException, InterruptedException {
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(Table.class);
configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
configuration.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
configuration.setProperty("hibernate.connection.url", "jdbc:h2:mem:test");
configuration.setProperty("hibernate.hbm2ddl.auto", "create");
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
this.sf = configuration.buildSessionFactory(serviceRegistry);
this.injector = Guice.createInjector(new CoreModule());
this.injector.injectMembers(this);
Key<SimpleScope> simpleScopeKey = Key.get(SimpleScope.class, Names.named("scriptingScope"));
this.scope = this.injector.getInstance(simpleScopeKey);
}
#After
public void tearDown() throws Exception {
this.sf.close();
}
Table.java
#Entity
#Table(schema = "internal", name = "table")
public class Table {
#Id
private Long id;
#Column(name = "name")
private String name;
}
Error
Schema "RIS" not found; SQL statement:
create table internal.table (id bigint not null, name varchar(255), primary key (id)) [90079-193]
Feb 13, 2017 10:52:20 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Solution for this problem can be found here: https://touk.pl/blog/2011/01/18/hibernate-hbm2ddl-wont-create-schema-before-creating-tables/

Categories

Resources