Я хочу использовать api rest и EntityManager в том же проекте весенней загрузки, с базой данных sqlite, поэтому мне удалось поднять остальные API с помощью spring-boot-starter-data-rest, которые я могу использовать из контроллер или с вызовами http, но мне также нужно использовать базу данных в моих java классах, которые не содержат весенних аннотаций.
Я хочу добавить, что у меня есть настольное приложение java с jpa и Я могу использовать менеджер сущностей обычным способом, но мне не удалось сделать это в весеннем проекте.
Я хочу подчеркнуть, что при использовании API я могу получать, создавать, обновлять и удалять данные из bd, через http звонки через почтальона, но когда я делаю это в методе на рабочем столе java, ответ пуст
, это пустой ответ из журнала
2020-04-20 12:00:11.014 INFO 4772 --- [nio-8080-exec-4] ProductToolApp.App :
Initialize Log
get DB
[EL Info]: 2020-04-20 12:00:11.184--ServerSession(896895170)--EclipseLink, version: Eclipse
Persistence Services - 2.7.6.v20200131-b7c997804f
[EL Info]: connection: 2020-04-20 12:00:11.185--Not able to detect platform for vendor name
[SQLite[3.15.1, 3]]. Defaulting to [org.eclipse.persistence.platform.database.DatabasePlatform]. The database dialect used may not match with the database you are using. Please explicitly provide a platform using property "eclipselink.target-database".
[EL Info]: connection: 2020-04-20 12:00:11.187--ServerSession(896895170)--/file:/C:/Users/myuser/eclipse-workspace/producttool/target/classes/_productToolPU login successful
enter to bd
[]
ниже зависимости в pom. xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.xerial/sqlite-jdbc -->
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.eclipse.persistence/javax.persistence -->
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.eclipse.persistence/org.eclipse.persistence.jpa -->
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
<version>2.7.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.zsoltfabok/sqlite-dialect -->
<dependency>
<groupId>com.zsoltfabok</groupId>
<artifactId>sqlite-dialect</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
ниже aplicattion.properties
# Upload file max size
spring.http.multipart.max-file-size=10MB
spring.http.multipart.max-request-size=10MB
# SQLite Conection
spring.datasource.url=jdbc:sqlite:src/main/resources/database/producttool.db
spring.jpa.database-platform=ProductTool.Controllers.Configuration.SQLiteDialect
#spring.jpa.hibernate.ddl-auto=create-drop
# Data Rest
spring.data.rest.base-path: /api
ниже моей модели BussinesLine
package ProductTool.Models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.data.rest.core.annotation.RestResource;
@Entity
@Table(name = "bussinesline")
@RestResource(rel="bussinesline", path="bussinesline")
public class BussinesLine {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String classXml;
public BussinesLine() {
}
public BussinesLine(int id, String name, String classXml) {
this.id = id;
this.name = name;
this.classXml = classXml;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassXml() {
return classXml;
}
public void setClassXml(String classXml) {
this.classXml = classXml;
}
}
ниже упорство.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="productToolPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>ProductTool.Models.BussinesLine</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.sqlite.JDBC" />
<property name="javax.persistence.jdbc.url" value="jdbc:sqlite:src/main/resources/database/producttool.db" />
<property name="eclipselink.logging.level" value="INFO"/>
</properties>
</persistence-unit>
</persistence>
ниже SQLiteDialect
package ProductTool.Controllers.Configuration;
import java.sql.Types;
import org.hibernate.Hibernate;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.dialect.function.VarArgsSQLFunction;
import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType;
public class SQLiteDialect extends Dialect {
public SQLiteDialect() {
registerColumnType(Types.BIT, "integer");
registerColumnType(Types.TINYINT, "tinyint");
registerColumnType(Types.SMALLINT, "smallint");
registerColumnType(Types.INTEGER, "integer");
registerColumnType(Types.BIGINT, "bigint");
registerColumnType(Types.FLOAT, "float");
registerColumnType(Types.REAL, "real");
registerColumnType(Types.DOUBLE, "double");
registerColumnType(Types.NUMERIC, "numeric");
registerColumnType(Types.DECIMAL, "decimal");
registerColumnType(Types.CHAR, "char");
registerColumnType(Types.VARCHAR, "varchar");
registerColumnType(Types.LONGVARCHAR, "longvarchar");
registerColumnType(Types.DATE, "date");
registerColumnType(Types.TIME, "time");
registerColumnType(Types.TIMESTAMP, "timestamp");
registerColumnType(Types.BINARY, "blob");
registerColumnType(Types.VARBINARY, "blob");
registerColumnType(Types.LONGVARBINARY, "blob");
// registerColumnType(Types.NULL, "null");
registerColumnType(Types.BLOB, "blob");
registerColumnType(Types.CLOB, "clob");
registerColumnType(Types.BOOLEAN, "integer");
registerFunction( "concat", new VarArgsSQLFunction(StringType.INSTANCE, "", "||", "") );
registerFunction( "mod", new SQLFunctionTemplate( StringType.INSTANCE, "?1 % ?2" ) );
registerFunction( "substr", new StandardSQLFunction("substr", StringType.INSTANCE) );
registerFunction( "substring", new StandardSQLFunction( "substr", StringType.INSTANCE) );
}
public boolean supportsIdentityColumns() {
return true;
}
/*
* public boolean supportsInsertSelectIdentity() { return true; // As
* specify in NHibernate dialect }
*/
public boolean hasDataTypeInIdentityColumn() {
return false; // As specify in NHibernate dialect
}
/*
* public String appendIdentitySelectToInsert(String insertString) { return
* new StringBuffer(insertString.length()+30). // As specify in NHibernate
* dialect append(insertString).
* append("; ").append(getIdentitySelectString()). toString(); }
*/
public String getIdentityColumnString() {
// return "integer primary key autoincrement";
return "integer";
}
public String getIdentitySelectString() {
return "select last_insert_rowid()";
}
public boolean supportsLimit() {
return true;
}
protected String getLimitString(String query, boolean hasOffset) {
return new StringBuffer(query.length() + 20).append(query)
.append(hasOffset ? " limit ? offset ?" : " limit ?")
.toString();
}
public boolean supportsTemporaryTables() {
return true;
}
public String getCreateTemporaryTableString() {
return "create temporary table if not exists";
}
public boolean dropTemporaryTableAfterUse() {
return false;
}
public boolean supportsCurrentTimestampSelection() {
return true;
}
public boolean isCurrentTimestampSelectStringCallable() {
return false;
}
public String getCurrentTimestampSelectString() {
return "select current_timestamp";
}
public boolean supportsUnionAll() {
return true;
}
public boolean hasAlterTable() {
return false; // As specify in NHibernate dialect
}
public boolean dropConstraints() {
return false;
}
public String getAddColumnString() {
return "add column";
}
public String getForUpdateString() {
return "";
}
public boolean supportsOuterJoinForUpdate() {
return false;
}
public String getDropForeignKeyString() {
throw new UnsupportedOperationException(
"No drop foreign key syntax supported by SQLiteDialect");
}
public String getAddForeignKeyConstraintString(String constraintName,
String[] foreignKey, String referencedTable, String[] primaryKey,
boolean referencesPrimaryKey) {
throw new UnsupportedOperationException(
"No add foreign key syntax supported by SQLiteDialect");
}
public String getAddPrimaryKeyConstraintString(String constraintName) {
throw new UnsupportedOperationException(
"No add primary key syntax supported by SQLiteDialect");
}
public boolean supportsIfExistsBeforeTableName() {
return true;
}
public boolean supportsCascadeDelete() {
return false;
}
}
ниже моего метода для получения данных из базы данных из JPA, здесь не приводятся данные из таблицы bussinesLine, она пуста
private void bussinesLineDB() {
System.out.println("get DB");
EntityManagerFactory emf;
emf = Persistence.createEntityManagerFactory("productToolPU");
em = emf.createEntityManager();
try {
CriteriaQuery<Object> cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(BussinesLine.class));
Query q = em.createQuery(cq);
System.out.println("enter to bd");
System.out.println(q.getResultList());
List<Object> resultList = (List<Object>)q.getResultList();
for (Object element : resultList) {
System.out.println("result: " + ((BussinesLine) element).getName());
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("Error db: " + e);
}
finally {
em.close();
}
}