无法在Spring Boot中实现Drools KieSession持久化

huangapple go评论89阅读模式
英文:

Cannot implement Drools KieSession Persistence in Spring Boot

问题

@Configuration
public class PersistentDroolConfig {

    // ... (The rest of the code remains the same)
}
@RestController
public class OfferController {

    // ... (The rest of the code remains the same)
}
public class Order implements Serializable {

    // ... (The rest of the code remains the same)
}
    <!-- Dependencies in pom.xml -->
Caused by: org.hibernate.engine.jndi.JndiException: Unable to lookup JNDI name [jdbc/BitronixJTADataSource]
Caused by: javax.naming.NameNotFoundException: unable to find a bound object at name 'jdbc/BitronixJTADataSource'
Caused by: org.hibernate.HibernateException: Unable to perform isolated work
Caused by: java.sql.SQLSyntaxErrorException: Table 'drool_demo.sessioninfo_id_seq' doesn't exist
Hibernate: drop table if exists SessionInfo
Hibernate: drop table if exists WorkItemInfo
Hibernate: create table SessionInfo (id bigint not null auto_increment, lastModificationDate datetime, rulesByteArray longblob, startDate datetime, OPTLOCK integer, primary key (id)) type=MyISAM
2020-10-09 23:49:59.554  WARN 11376 --- [           main] o.h.t.s.i.ExceptionHandlerLoggedImpl     : GenerationTarget encountered exception accepting command : Error executing DDL "create table SessionInfo (id bigint not null auto_increment, lastModificationDate datetime, rulesByteArray longblob, startDate datetime, OPTLOCK integer, primary key (id)) type=MyISAM" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table SessionInfo (id bigint not null auto_increment, lastModificationDate datetime, rulesByteArray longblob, startDate datetime, OPTLOCK integer, primary key (id)) type=MyISAM" via JDBC Statement
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'type=MyISAM' at line 1
Hibernate: create table WorkItemInfo (workItemId bigint not null auto_increment, creationDate datetime, name varchar(255), processInstanceId bigint not null, state bigint not null, OPTLOCK integer, workItemByteArray longblob, primary key (workItemId)) type=MyISAM
2020-10-09 23:49:59.556  WARN 11376 --- [           main] o.h.t.s.i.ExceptionHandlerLoggedImpl     : GenerationTarget encountered exception accepting command : Error executing DDL "create table WorkItemInfo (workItemId bigint not null auto_increment, creationDate datetime, name varchar(255), processInstanceId bigint not null, state bigint not null, OPTLOCK integer, workItemByteArray longblob, primary key (workItemId)) type=MyISAM" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table WorkItemInfo (workItemId bigint not null auto_increment, creationDate datetime, name varchar(255), processInstanceId bigint not null, state bigint not null, OPTLOCK integer, workItemByteArray longblob, primary key (workItemId)) type=MyISAM" via JDBC Statement
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'type=MyISAM' at line 1
英文:

I was trying to implement Drools with the persistence feature of KieSession, in a Spring Boot Maven project. Followed this documentation for the implementation. Was able to do that in a normal Java application but I am getting exceptions while trying to do that in a Spring Boot application.

Below is the implementation.

The project structure

无法在Spring Boot中实现Drools KieSession持久化

Configuration class

@Configuration
public class PersistentDroolConfig {

    public static Long KIE_SESSION_ID;
    private final KieServices kieServices = KieServices.Factory.get();

    @Bean
    public KieSession kieSession() {
        KieSession kieSession = kieServices.getStoreServices().newKieSession(getKieBase(), null, getEnv());
        PersistentDroolConfig.KIE_SESSION_ID = kieSession.getIdentifier();
        return kieSession;
    }

    public KieServices getKieServices() {
        initDataSource();
        return kieServices;
    }

    public KieBase getKieBase() {
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
        kieFileSystem.write(ResourceFactory.newClassPathResource(&quot;rules/rules.drl&quot;));
        final KieRepository kieRepository = kieServices.getRepository();
        kieRepository.addKieModule(kieRepository::getDefaultReleaseId);
        KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);
        kb.buildAll();
        KieModule kieModule = kb.getKieModule();
        KieContainer kieContainer = kieServices.newKieContainer(kieModule.getReleaseId());
        return kieContainer.getKieBase();
    }

    public Environment getEnv() {
        Environment env = kieServices.newEnvironment();
        env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, Persistence.createEntityManagerFactory(&quot;org.drools.persistence.jpa&quot;));
        env.set(EnvironmentName.TRANSACTION_MANAGER, TransactionManagerServices.getTransactionManager());
        return env;
    }

    private void initDataSource() {
        PoolingDataSource ds = new PoolingDataSource();
        ds.setUniqueName(&quot;jdbc/BitronixJTADataSource&quot;);
        ds.setClassName(&quot;com.mysql.cj.jdbc.MysqlXADataSource&quot;);
        ds.setMaxPoolSize(3);
        ds.setAllowLocalTransactions(true);
        ds.getDriverProperties().put(&quot;user&quot;, &quot;root&quot;);
        ds.getDriverProperties().put(&quot;password&quot;, &quot;1234&quot;);
        ds.getDriverProperties().put(&quot;URL&quot;, &quot;jdbc:mysql://localhost:3306/drool_demo&quot;);
        ds.init();
    }
}

Controller class

@RestController
public class OfferController {

    @Autowired
    private KieSession kieSession;

    @GetMapping(&quot;/order/{card-type}/{price}&quot;)
    public Order order(@PathVariable(&quot;card-type&quot;) String cardType, @PathVariable int price) {
        Order order = new Order(cardType, price);
        kieSession.insert(order);
        kieSession.fireAllRules();
        return order;
    }
}

Fact Class

public class Order implements Serializable {

    private String name;
    private String cardType;
    private int discount;
    private int price;

    public Order(String cardType, int price) {
        this.cardType = cardType;
        this.price = price;
    }

    // setters and getters

    // toString()
}

persistence.xml

&lt;persistence version=&quot;2.0&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd
                      http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd&quot;
	xmlns:orm=&quot;http://java.sun.com/xml/ns/persistence/orm&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns=&quot;http://java.sun.com/xml/ns/persistence&quot;&gt;
	&lt;persistence-unit name=&quot;org.drools.persistence.jpa&quot;
		transaction-type=&quot;JTA&quot;&gt;
		&lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt;
		&lt;jta-data-source&gt;jdbc/BitronixJTADataSource&lt;/jta-data-source&gt;
		&lt;class&gt;org.drools.persistence.info.SessionInfo&lt;/class&gt;
		&lt;class&gt;org.drools.persistence.info.WorkItemInfo&lt;/class&gt;
		&lt;properties&gt;
			&lt;property name=&quot;hibernate.dialect&quot; value=&quot;org.hibernate.dialect.MySQLDialect&quot; /&gt;
			&lt;property name=&quot;hibernate.max_fetch_depth&quot; value=&quot;3&quot; /&gt;
			&lt;property name=&quot;hibernate.hbm2ddl.auto&quot; value=&quot;create&quot; /&gt;
			&lt;property name=&quot;hibernate.show_sql&quot; value=&quot;true&quot; /&gt;
			&lt;property name=&quot;hibernate.transaction.manager_lookup_class&quot; value=&quot;org.hibernate.transaction.BTMTransactionManagerLookup&quot; /&gt;
		&lt;/properties&gt;
	&lt;/persistence-unit&gt;
&lt;/persistence&gt;

The dependencies included in pom.xml file is as follows:

    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;mysql&lt;/groupId&gt;
            &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
            &lt;scope&gt;runtime&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.github.marcus-nl.btm&lt;/groupId&gt;
            &lt;artifactId&gt;btm&lt;/artifactId&gt;
            &lt;version&gt;3.0.0-mk1&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.drools&lt;/groupId&gt;
            &lt;artifactId&gt;drools-decisiontables&lt;/artifactId&gt;
            &lt;version&gt;${drools-version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.drools&lt;/groupId&gt;
            &lt;artifactId&gt;drools-core&lt;/artifactId&gt;
            &lt;version&gt;${drools-version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.drools&lt;/groupId&gt;
            &lt;artifactId&gt;drools-compiler&lt;/artifactId&gt;
            &lt;version&gt;${drools-version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.drools&lt;/groupId&gt;
            &lt;artifactId&gt;drools-persistence-jpa&lt;/artifactId&gt;
            &lt;version&gt;${drools-version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
            &lt;exclusions&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.junit.vintage&lt;/groupId&gt;
                    &lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt;
                &lt;/exclusion&gt;
            &lt;/exclusions&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;

The error stacktrace:

Caused by: org.hibernate.engine.jndi.JndiException: Unable to lookup JNDI name [jdbc/BitronixJTADataSource]

Caused by: javax.naming.NameNotFoundException: unable to find a bound object at name &#39;jdbc/BitronixJTADataSource&#39;

The project also can be found here in this repository.

UPDATE 1:

After implementing @jccampanero 's answer, I have a newer stacktrace:

Caused by: org.hibernate.HibernateException: Unable to perform isolated work

Caused by: java.sql.SQLSyntaxErrorException: Table &#39;drool_demo.sessioninfo_id_seq&#39; doesn&#39;t exist

UPDATE 2:

After digging further, I have seen Drools isn't making the necessary tables because of some syntax error. Have posted only the important exception messages here since Stackoverflow has a text limit. Here's it is:

Hibernate: drop table if exists SessionInfo
Hibernate: drop table if exists WorkItemInfo
Hibernate: create table SessionInfo (id bigint not null auto_increment, lastModificationDate datetime, rulesByteArray longblob, startDate datetime, OPTLOCK integer, primary key (id)) type=MyISAM
2020-10-09 23:49:59.554  WARN 11376 --- [           main] o.h.t.s.i.ExceptionHandlerLoggedImpl     : GenerationTarget encountered exception accepting command : Error executing DDL &quot;create table SessionInfo (id bigint not null auto_increment, lastModificationDate datetime, rulesByteArray longblob, startDate datetime, OPTLOCK integer, primary key (id)) type=MyISAM&quot; via JDBC Statement


org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL &quot;create table SessionInfo (id bigint not null auto_increment, lastModificationDate datetime, rulesByteArray longblob, startDate datetime, OPTLOCK integer, primary key (id)) type=MyISAM&quot; via JDBC Statement

Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near &#39;type=MyISAM&#39; at line 1

Hibernate: create table WorkItemInfo (workItemId bigint not null auto_increment, creationDate datetime, name varchar(255), processInstanceId bigint not null, state bigint not null, OPTLOCK integer, workItemByteArray longblob, primary key (workItemId)) type=MyISAM
2020-10-09 23:49:59.556  WARN 11376 --- [           main] o.h.t.s.i.ExceptionHandlerLoggedImpl     : GenerationTarget encountered exception accepting command : Error executing DDL &quot;create table WorkItemInfo (workItemId bigint not null auto_increment, creationDate datetime, name varchar(255), processInstanceId bigint not null, state bigint not null, OPTLOCK integer, workItemByteArray longblob, primary key (workItemId)) type=MyISAM&quot; via JDBC Statement

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL &quot;create table WorkItemInfo (workItemId bigint not null auto_increment, creationDate datetime, name varchar(255), processInstanceId bigint not null, state bigint not null, OPTLOCK integer, workItemByteArray longblob, primary key (workItemId)) type=MyISAM&quot; via JDBC Statement

Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near &#39;type=MyISAM&#39; at line 1

答案1

得分: 2

我认为您的配置中存在问题。```PersistentDroolConfig``` 类的 ```getKieServices``` 方法从未被调用因此 ```initDataSource``` 方法也不会被调用该方法用于初始化数据源

也许您可以尝试修改您的 ```PersistentDroolConfig```,类似于以下内容

```java
@Configuration
public class PersistentDroolConfig {

    public static Long KIE_SESSION_ID;

    private KieServices kieServices;

    @PostContruct
    private void init() {
        this.initDataSource();
        this.kieServices = KieServices.Factory.get();
    }

    @Bean
    public KieSession kieSession() {
        KieSession kieSession;
        if (KIE_SESSION_ID == null) {
            kieSession = createNewKieSession();
            KIE_SESSION_ID = kieSession.getIdentifier();
            return kieSession;
        } else {
            kieSession = getPersistentKieSession();
            KIE_SESSION_ID = kieSession.getIdentifier();
            return kieSession;
        }
    }

    // 其他方法的翻译...
}

更新

根据不同的评论,进行了上述更改后,出现了与用于生成实体 SessionInfoSESSIONINFO_ID_SEQ 序列相关的问题。

问题似乎与使用的 Hibernate 版本和 MySQL 相关。

为了解决这个问题,需要对 persistence.xml 文件进行多处更改。

首先,应该包含以下属性:

<property name="hibernate.id.new_generator_mappings" value="false" />

这在 Drools 的示例和 测试用例 中经常使用。详细的解释请参见 Vlad Mihalcea 的 文章

添加此配置属性会引发一个与所使用的 MySQL 方言相关的新问题。需要将其更改为:

<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>

通过这个配置,应用程序应该可以顺利运行。


<details>
<summary>英文:</summary>
I think there is a problem in your configuration. The ```getKieServices``` method of the ```PersistentDroolConfig``` class is never invoked and, as a consequence, neither is the method ```initDataSource``` which initializes your datasource.
Maybe you can try to modify your ```PersistentDroolConfig```, something like this:
```java
@Configuration
public class PersistentDroolConfig {
public static Long KIE_SESSION_ID;
private KieServices kieServices;
@PostContruct
private void init() {
this.initDataSource();
this.kieServices = KieServices.Factory.get();
}
@Bean
public KieSession kieSession() {
KieSession kieSession;
if (KIE_SESSION_ID == null) {
kieSession = createNewKieSession();
KIE_SESSION_ID = kieSession.getIdentifier();
return kieSession;
} else {
kieSession = getPersistentKieSession();
KIE_SESSION_ID = kieSession.getIdentifier();
return kieSession;
}
}
public KieBase getKieBase() {
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
kieFileSystem.write(ResourceFactory.newClassPathResource(&quot;rules/rules.drl&quot;));
final KieRepository kieRepository = kieServices.getRepository();
kieRepository.addKieModule(new KieModule() {
@Override
public ReleaseId getReleaseId() {
return kieRepository.getDefaultReleaseId();
}
});
KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);
kb.buildAll();
KieModule kieModule = kb.getKieModule();
KieContainer kieContainer = kieServices.newKieContainer(kieModule.getReleaseId());
KieBase kieBase = kieContainer.getKieBase();
return kieBase;
}
public Environment getEnv() {
Environment env = kieServices.newEnvironment();
env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, Persistence.createEntityManagerFactory(&quot;org.drools.persistence.jpa&quot;));
env.set(EnvironmentName.TRANSACTION_MANAGER, TransactionManagerServices.getTransactionManager());
return env;
}
private KieSession createNewKieSession() {
KieSession kieSession = kieServices.getStoreServices().newKieSession(getKieBase(), null, getEnv());
PersistentDroolConfig.KIE_SESSION_ID = kieSession.getIdentifier();
return kieSession;
}
private KieSession getPersistentKieSession() {
return kieServices.getStoreServices().loadKieSession(KIE_SESSION_ID, getKieBase(), null, getEnv());
}
private void initDataSource() {
PoolingDataSource ds = new PoolingDataSource();
ds.setUniqueName(&quot;jdbc/BitronixJTADataSource&quot;);
ds.setClassName(&quot;com.mysql.cj.jdbc.MysqlXADataSource&quot;);
ds.setMaxPoolSize(3);
ds.setAllowLocalTransactions(true);
ds.getDriverProperties().put(&quot;user&quot;, &quot;root&quot;);
ds.getDriverProperties().put(&quot;password&quot;, &quot;1234&quot;);
ds.getDriverProperties().put(&quot;URL&quot;, &quot;jdbc:mysql://localhost:3306/drool_demo&quot;);
ds.init();
}
}

UPDATE

As stated in the different comments, after making these changes, a problem arose related to the SESSIONINFO_ID_SEQ sequence used to generate the values of the field id of the entity SessionInfo.

The problem seemed to be related to the version of Hibernate and MySQL used.

To solve the problem, it is necessary to make several changes to the persistence.xml file.

First, the following property should be included:

&lt;property name=&quot;hibernate.id.new_generator_mappings&quot; value=&quot;false&quot; /&gt;

It is often used in the Drools examples and test cases. See this great Vlad Mihalcea article for an in depth explanation.

The inclusion of this configuration property generated a new problem related to the MySQL dialect used. It should be changed to:

&lt;property name=&quot;hibernate.dialect&quot; value=&quot;org.hibernate.dialect.MySQL5Dialect&quot;/&gt;

With this configuration, the application should run smoothly.

答案2

得分: 1

你在容器中配置了JNDI数据源吗?

<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
    maxTotal="100" maxIdle="30" maxWaitMillis="10000"
    username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/javatest"/>

Tomcat JNDI数据源示例

英文:

Did you configure jndi datasource in your container?

&lt;Resource name=&quot;jdbc/TestDB&quot; auth=&quot;Container&quot; type=&quot;javax.sql.DataSource&quot;
maxTotal=&quot;100&quot; maxIdle=&quot;30&quot; maxWaitMillis=&quot;10000&quot;
username=&quot;javauser&quot; password=&quot;javadude&quot; driverClassName=&quot;com.mysql.jdbc.Driver&quot;
url=&quot;jdbc:mysql://localhost:3306/javatest&quot;/&gt;

Tomcat jndi data source example

huangapple
  • 本文由 发表于 2020年10月6日 16:07:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/64221767.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定