Getting error: Class 'models.forumModels.Phpbb_forums' is not mapped - sqlmodel

i create a scripts to add data into my database with sqlmoel, i've 2 table one posts and the other forums, for the posts script worked normally without any problem but the forum script it return an error that the table forums is not mapped.
here is my code and error:
forums model
from typing import Optional
from sqlmodel import Field, SQLModel
class Phpbb_forums(SQLModel, Table=True):
__tablename__ = 'phpbb_forums'
forum_id: Optional[int] = Field(default=None, primary_key=True)
parent_id: int = '0'
left_id: Optional[int] = Field(default=None, primary_key=True)
right_id: Optional[int] = Field(default=None, primary_key=True)
forum_parents: str
forum_name: str
forum_desc: str
forum_desc_bitfield: str = ''
forum_desc_options: int = '7'
forum_desc_uid: str = ''
forum_link: str = ''
forum_password: str = ''
forum_style: int = '0'
forum_image: str = ''
forum_rules: str = ''
forum_rules_link: str = ''
forum_rules_bitfield: str = ''
forum_rules_options: int = '7'
forum_rules_uid: str = ''
forum_topics_per_page: int = '0'
forum_type: int = '0'
forum_status: int = '0'
forum_last_post_id: Optional[int] = Field(default=None, primary_key=True)
forum_last_poster_id: int = '0'
forum_last_post_subject: str = ''
forum_last_post_time: int = '0'
forum_last_poster_name: str = ''
forum_last_poster_colour: str = ''
forum_flags: int = '32'
display_on_index: int = '1'
enable_indexing: int = '1'
enable_icons: int = '1'
enable_prune: int = '0'
prune_next: int = '0'
prune_days: int = '0'
prune_viewed: int = '0'
prune_freq: int = '0'
display_subforum_list: int = '1'
display_subforum_limit: int = '0'
forum_options: int = '0'
enable_shadow_prune: int = '0'
prune_shadow_days: int = '7'
prune_shadow_freq: int = '1'
prune_shadow_next: int = '0'
forum_posts_approved: int = '0'
forum_posts_unapproved: int = '0'
forum_posts_softdeleted: int = '0'
forum_topics_approved: int = '0'
forum_topics_unapproved: int = '0'
forum_topics_softdeleted: int = '0'
script to add to database
from sqlmodel import Session
from models.forumModels import Phpbb_forums
from db import engine
parent_id = 4 # id of categorie series and '6' for films
parent_name = 'Series' # name of categorie Series and 'Films' for films
def create_forum():
forum = Phpbb_forums(
# parent_id=parent_id,
forum_parents=parent_name,
forum_name='vikings',
forum_desc='la serie de vikings '
)
# with Session(engine) as session:
session = Session(engine)
if session:
print("session:", session)
try:
session.add(forum)
print("success adding")
except Exception as e:
session.rollback()
print("error:", str(e))
try:
session.commit()
print("success commit")
except Exception as e:
session.rollback()
print("error:", str(e))
def main():
create_forum()
if __name__ == "__main__":
main()
and this is my table in database
CREATE TABLE `phpbb_forums` (
`forum_id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT,
`parent_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0',
`left_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0',
`right_id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0',
`forum_parents` MEDIUMTEXT NOT NULL COLLATE 'utf8mb3_bin',
`forum_name` VARCHAR(255) NOT NULL DEFAULT '' COLLATE 'utf8mb3_bin',
`forum_desc` TEXT NOT NULL COLLATE 'utf8mb3_bin',
`forum_desc_bitfield` VARCHAR(255) NOT NULL DEFAULT '' COLLATE 'utf8mb3_bin',
`forum_desc_options` INT(11) UNSIGNED NOT NULL DEFAULT '7',
`forum_desc_uid` VARCHAR(8) NOT NULL DEFAULT '' COLLATE 'utf8mb3_bin',
`forum_link` VARCHAR(255) NOT NULL DEFAULT '' COLLATE 'utf8mb3_bin',
`forum_password` VARCHAR(255) NOT NULL DEFAULT '' COLLATE 'utf8mb3_bin',
`forum_style` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0',
`forum_image` VARCHAR(255) NOT NULL DEFAULT '' COLLATE 'utf8mb3_bin',
`forum_rules` TEXT NOT NULL COLLATE 'utf8mb3_bin',
`forum_rules_link` VARCHAR(255) NOT NULL DEFAULT '' COLLATE 'utf8mb3_bin',
`forum_rules_bitfield` VARCHAR(255) NOT NULL DEFAULT '' COLLATE 'utf8mb3_bin',
`forum_rules_options` INT(11) UNSIGNED NOT NULL DEFAULT '7',
`forum_rules_uid` VARCHAR(8) NOT NULL DEFAULT '' COLLATE 'utf8mb3_bin',
`forum_topics_per_page` SMALLINT(4) UNSIGNED NOT NULL DEFAULT '0',
`forum_type` TINYINT(4) NOT NULL DEFAULT '0',
`forum_status` TINYINT(4) NOT NULL DEFAULT '0',
`forum_last_post_id` INT(10) UNSIGNED NOT NULL DEFAULT '0',
`forum_last_poster_id` INT(10) UNSIGNED NOT NULL DEFAULT '0',
`forum_last_post_subject` VARCHAR(255) NOT NULL DEFAULT '' COLLATE 'utf8mb3_bin',
`forum_last_post_time` INT(11) UNSIGNED NOT NULL DEFAULT '0',
`forum_last_poster_name` VARCHAR(255) NOT NULL DEFAULT '' COLLATE 'utf8mb3_bin',
`forum_last_poster_colour` VARCHAR(6) NOT NULL DEFAULT '' COLLATE 'utf8mb3_bin',
`forum_flags` TINYINT(4) NOT NULL DEFAULT '32',
`display_on_index` TINYINT(1) UNSIGNED NOT NULL DEFAULT '1',
`enable_indexing` TINYINT(1) UNSIGNED NOT NULL DEFAULT '1',
`enable_icons` TINYINT(1) UNSIGNED NOT NULL DEFAULT '1',
`enable_prune` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
`prune_next` INT(11) UNSIGNED NOT NULL DEFAULT '0',
`prune_days` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0',
`prune_viewed` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0',
`prune_freq` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0',
`display_subforum_list` TINYINT(1) UNSIGNED NOT NULL DEFAULT '1',
`display_subforum_limit` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
`forum_options` INT(20) UNSIGNED NOT NULL DEFAULT '0',
`enable_shadow_prune` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
`prune_shadow_days` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '7',
`prune_shadow_freq` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '1',
`prune_shadow_next` INT(11) NOT NULL DEFAULT '0',
`forum_posts_approved` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0',
`forum_posts_unapproved` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0',
`forum_posts_softdeleted` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0',
`forum_topics_approved` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0',
`forum_topics_unapproved` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0',
`forum_topics_softdeleted` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (`forum_id`) USING BTREE,
INDEX `left_right_id` (`left_id`, `right_id`) USING BTREE,
INDEX `forum_lastpost_id` (`forum_last_post_id`) USING BTREE
)
COLLATE='utf8mb3_bin'
ENGINE=InnoDB
AUTO_INCREMENT=9
;
the error:
session: <sqlmodel.orm.session.Session object at 0x000002105BB29450>
error: Class 'models.forumModels.Phpbb_forums' is not mapped
success commit
where is the problem?
I'm still new my knowledge is limited please help me.

Related

SQL subquery filters data but conversion to JPA with subquery does not filter

Tree, Treetag and Tag tables with example data
A tree belongs to a given farm and each farm has its own set of tags.
Each tree can have zero or multiple tags attached to it.
Same tag can be attached to multiple trees.
DDL -
DROP TABLE tree_tag;
DROP TABLE tag;
DROP TABLE tree;
DROP TABLE farm;
CREATE TABLE farm (
id VARCHAR2(36 CHAR) NOT NULL,
description VARCHAR2(255 CHAR) NULL,
name VARCHAR2(255 CHAR) NOT NULL,
PRIMARY KEY ( id )
);
CREATE TABLE tree (
id VARCHAR2(36 CHAR) NOT NULL,
name VARCHAR2(255 CHAR) NOT NULL,
description VARCHAR2(255 CHAR) NULL,
farm_id VARCHAR2(36 CHAR) NOT NULL,
PRIMARY KEY ( id )
);
CREATE TABLE tag (
id VARCHAR2(36 CHAR) NOT NULL,
farm_id VARCHAR2(36 CHAR) NOT NULL,
name VARCHAR2(255 CHAR) NOT NULL,
description VARCHAR2(255 CHAR) NULL,
PRIMARY KEY ( id )
);
CREATE TABLE tree_tag (
id VARCHAR2(36 CHAR) NOT NULL,
tag_id VARCHAR2(36 CHAR) NOT NULL,
tree_id VARCHAR2(36 CHAR) NOT NULL,
value VARCHAR2(255 CHAR) NULL,
properties VARCHAR2(1000 CHAR) NULL,
PRIMARY KEY ( id )
);
ALTER TABLE tag ADD CONSTRAINT unq_tag0 UNIQUE ( farm_id,
name );
ALTER TABLE tree_tag ADD CONSTRAINT unq_tree_tag0 UNIQUE ( tag_id,
tree_id );
ALTER TABLE tree ADD CONSTRAINT unq_tree0 UNIQUE ( farm_id,
name );
ALTER TABLE tag
ADD CONSTRAINT fk_tagfarm_id FOREIGN KEY ( farm_id )
REFERENCES farm ( id )
ON DELETE CASCADE;
ALTER TABLE tree_tag
ADD CONSTRAINT fk_tree_tagtree_id FOREIGN KEY ( tree_id )
REFERENCES tree ( id )
ON DELETE CASCADE;
ALTER TABLE tree_tag
ADD CONSTRAINT fk_tree_tagtag_id FOREIGN KEY ( tag_id )
REFERENCES tag ( id )
ON DELETE CASCADE;
INSERT INTO farm (
id,
name
) VALUES (
'farm1',
'farm 1 is big'
);
INSERT INTO farm (
id,
name
) VALUES (
'farm2',
'farm 2 is small'
);
INSERT INTO tag (
id,
farm_id,
name
) VALUES (
'tag11',
'farm1',
'juicy'
);
INSERT INTO tag (
id,
farm_id,
name
) VALUES (
'tag12',
'farm1',
'sour'
);
INSERT INTO tag (
id,
farm_id,
name
) VALUES (
'tag13',
'farm1',
'sweet'
);
INSERT INTO tag (
id,
farm_id,
name
) VALUES (
'tag21',
'farm2',
'sour'
);
INSERT INTO tree (
id,
farm_id,
name,
description
) VALUES (
'tree11',
'farm1',
'apple',
'used for jam'
);
INSERT INTO tree (
id,
farm_id,
name
) VALUES (
'tree12',
'farm1',
'cherry'
);
INSERT INTO tree (
id,
farm_id,
name
) VALUES (
'tree13',
'farm1',
'plum'
);
INSERT INTO tree (
id,
farm_id,
name
) VALUES (
'tree21',
'farm2',
'apple'
);
INSERT INTO tree_tag (
id,
tree_id,
tag_id
) VALUES (
'1',
'tree11',
'tag12'
);
INSERT INTO tree_tag (
id,
tree_id,
tag_id
) VALUES (
'2',
'tree12',
'tag11'
);
INSERT INTO tree_tag (
id,
tree_id,
tag_id
) VALUES (
'3',
'tree12',
'tag13'
);
INSERT INTO tree_tag (
id,
tree_id,
tag_id
) VALUES (
'4',
'tree13',
'tag12'
);
INSERT INTO tree_tag (
id,
tree_id,
tag_id
) VALUES (
'5',
'tree13',
'tag11'
);
Query:
Want to get a list of trees w/o duplicates where either the name
or the description or the tag name matches the filter in a given
farm
Want to get the count of this unique list of trees in a
given farm
This is a paging request so step 1 query will be called multiple times but step 2 query will be executed only once.
SQL -
This works but when I convert to JPA then subquery is returning all the entries in tree_tag i.e filtering is not happening in JPA subquery
SELECT
t.farm_id,
t.id,
t.name,
t.description
FROM
tree t
WHERE
t.farm_id = :farmid
AND ( lower(t.name) LIKE '%'
|| lower(:filter)
|| '%'
OR lower(t.description) LIKE '%'
|| lower(:filter)
|| '%'
OR ( t.id IN (
SELECT DISTINCT
tt.tree_id
FROM
tree_tag tt, tag ttag
WHERE
tt.tag_id = ttag.id
AND lower(ttag.name) LIKE '%'
|| lower(:filter)
|| '%'
) ) );
SELECT
COUNT(*)
FROM
tree t
WHERE
t.farm_id = :farmid
AND ( lower(t.name) LIKE '%'
|| lower(:filter)
|| '%'
OR lower(t.description) LIKE '%'
|| lower(:filter)
|| '%'
OR ( t.id IN (
SELECT DISTINCT
tt.tree_id
FROM
tree_tag tt, tag ttag
WHERE
tt.tag_id = ttag.id
AND lower(ttag.name) LIKE '%'
|| lower(:filter)
|| '%'
) ) );
JPA -
void buildQuery(EntityManager em, String farmId, String filter) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tree> cq = cb.createQuery(Tree.class);
Root<Tree> tree = cq.from(Tree.class);
List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.equal(tree.get("farm").get("id"), farmId));
Predicate namePredicate = cb.like(tree.get(Tree_.name), "%"+filter+"%");
Predicate descriptionPredicate = cb.like(tree.get(Tree_.description), "%"+filter+"%");
Subquery<String> subQuery = cq.subquery(String.class);
Root<TreeTag> treeTagRoot = subQuery.from(TreeTag.class);
Join<TreeTag, Tag> treeTagTagJoin = treeTagRoot.join(TreeTag_.tag);
List<Predicate> subPredicates = new ArrayList<>();
subPredicates.add(cb.equal(treeTagRoot.get(TreeTag_.tag).get(Tag_.id), treeTagTagJoin.get(Tag_.id)));
subPredicates.add(cb.like(treeTagTagJoin.get(Tag_.name), "%"+filter+"%"));
subQuery.select(treeTagRoot.get(Treetag_.tree).get(Tree_.id)).distinct(true).where(subPredicates.toArray(new Predicate[0]));
Predicate inSubQueryPredicate = tree.get(Tree_.id).in(subQuery);
predicates.add(cb.or(namePredicate, descriptionPredicate, inSubQueryPredicate));
cq = cq.where(predicates.toArray(new Predicate[0]));
cq = cq.orderBy(request.buildOrderBy(cb, tree));
TypedQuery<Tree> query = em.createQuery(cq);
List<Tree> trees = query.getResultList();
// for count - using the same query as above but replacing above 2 lines as
// cq = cq.select(cb.count(tree));
// TypedQuery<Long> query = em.createQuery(cq);
// int count = query.getSingleResult().intValue();
}
Entity Classes -
#Entity
#Table(name = "FARM"))
public class Farm {
#Id
#Column(name = "ID")
String id;
public static final String NAME = "name";
public static final String DESCRIPTION = "description";
}
#Entity
#Table(name = "TAG", uniqueConstraints = #UniqueConstraint(columnNames = {"FARM_ID", "NAME"}))
public class Tag {
#Id
#Column(name = "ID")
String id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "FARM_ID", nullable = false, updatable = false)
Farm farm;
#Column(name = "NAME")
protected String name;
#Column(name = "DESCRIPTION")
private String description;
#OneToMany(mappedBy = "tag", fetch = FetchType.LAZY)
#CascadeOnDelete
private List<TreeTag> treeTagList = new ArrayList<>();
}
#MappedSuperclass
public abstract class ResourceTag {
#Id
#Column(name = "ID")
String id;
#ManyToOne
#JoinColumn(name = "TAG_ID", nullable = false)
protected Tag tag;
#Column(name = "VALUE")
protected String value;
}
#Entity
#Table(name = "TREE_TAG", uniqueConstraints = #UniqueConstraint(columnNames = {"TAG_ID", "TREE_ID"}))
public class TreeTag extends ResourceTag {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "TREE_ID", nullable = false)
private Tree tree;
}
#Entity
#Table(name="TREE",uniqueConstraints = #UniqueConstraint(columnNames = {"NAME”,"FARM_ID"}))
public class Tree {
#Id
#Column(name = "ID")
String id;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name = "FARM_ID", nullable = false)
Farm farm;
#Column(name= "NAME", nullable=false)
private String name;
#Column(name = "DESCRIPTION")
private String description;
#OneToMany(mappedBy = "tree", fetch = FetchType.LAZY)
#CascadeOnDelete
#BatchFetch(value=BatchFetchType.JOIN)
private List<TreeTag> treeTagList = new ArrayList<>();
}
How can I make this JPA code work for both the list and count? Thanks

Execute array into DB by Dapper

If string Subject = "Hello"; and int[] Category = new int[] { 1, 3, 5, 7, 9 };
How can i insert above variables into DB with one execute session? (i'm using Dapper)
My sql stored procedure:
CREATE PROCEDURE [dbo].[TKNewTicket]
#Subject nvarchar(max),
#Category int
AS
BEGIN
SET NOCOUNT ON;
DECLARE #ObjectID [int]
INSERT INTO dbo.TKTickets(Subject) VALUES (#Subject)
SET #ObjectID = SCOPE_IDENTITY()
INSERT INTO dbo.TKTicketCategory(TicketId, CategoryId) VALUES(#ObjectID, #Category)
END
GO
My Tables:
CREATE TABLE [dbo].[TKTickets] (
[Id] INT NOT NULL PRIMARY KEY IDENTITY,
[Subject] nvarchar(100) NOT NULL, )
CREATE TABLE [dbo].[TKTicketCategory] (
[Id] INT NOT NULL PRIMARY KEY IDENTITY,
[TicketId] INT NULL,
[CategoryId] INT NULL,
CONSTRAINT [FK_TKTicketCategory_TKTickets] FOREIGN KEY ([TicketId]) REFERENCES [TKTickets]([Id]),
CONSTRAINT [FK_TKTicketCategory_TKCategories] FOREIGN KEY ([CategoryId]) REFERENCES [TKCategories]([Id]), )
I figured out.
public static void NewTicket(string Subject, int[] Categories)
{
using (IDbConnection cnn = new SqlConnection(SqlDataAccess.GetConnectionString()))
{
string sql = #"dbo.InsertNewTicket #Subject";
var ObjectId = cnn.Query<int>(sql, new { Subject = Subject }).Single();
foreach(int Category in Categories)
{
sql = #"InsertNewTicketCategory #TicketId, #CategoryId";
cnn.Query(sql, new { TicketId = ObjectId, CategoryId = Category });
}
}
}

JPA - I get multiple rows instead of 1

I spent many hours to solve my problem but without success. I'd like to achieve something like this (but with ONE row instead of TWO):
My database:
CREATE TABLE odo.d_kryterium_naruszen (
id bigserial primary key,
kryterium text not null,
data_wpr TIMESTAMP not null DEFAULT clock_timestamp(),
opr bigint not null
);
CREATE TABLE odo.d_czynnik_naruszen (
id bigserial primary key,
czynnik text not null,
id_kryterium_naruszen bigint not null references odo.d_kryterium_naruszen(id),
stopien NUMERIC(10,2) not null,
data_wpr TIMESTAMP not null DEFAULT clock_timestamp(),
opr bigint not null
);
CREATE TABLE odo.d_dotkliwosc_naruszenia (
id bigserial primary key,
zakres numrange not null,
ocena text not null,
opis text not null,
wymagane_dzialanie text not null,
data_wpr TIMESTAMP not null DEFAULT clock_timestamp(),
opr bigint not null
);
CREATE TABLE odo.ocena_naruszenia_wynik (
id bigserial primary key,
wartosc_dotkliwosci_naruszenia NUMERIC(10,2) not null,
status_id bigint not null references odo.d_status_oceny_naruszenia(id),
ocena_naruszenia_id bigint not null references odo.ocena_naruszenia(id),
data_wpr TIMESTAMP not null DEFAULT clock_timestamp(),
opr bigint not null
);
create table odo.czynnik_naruszen_wynik(
id bigserial primary key,
ocena_naruszenia_wynik_id bigint not null references odo.ocena_naruszenia_wynik(id),
czynnik_naruszen_id bigint not null references odo.d_czynnik_naruszen(id),
komentarz text,
czynnik_wybrany boolean not null default false
wartosc_wybrana NUMERIC(10,2) not null,
data_wpr TIMESTAMP not null DEFAULT clock_timestamp(),
opr bigint not null
);
And here my entities:
#Data
#Entity
#Table(schema = "odo", name = "d_kryterium_naruszen")
public class ViolationCriterion extends BaseEntity {
#Column(name = "kryterium")
private String criterion;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
#JoinColumn(name = "id_kryterium_naruszen")
private List<ViolationFactor> violationFactors;
}
#Data
#Entity
#Table(schema = "odo", name = "d_czynnik_naruszen")
public class ViolationFactor extends BaseEntity {
#Column(name = "czynnik")
private String factor;
#Column(name = "stopien")
private float degree;
#OneToMany
#JoinColumn(name = "czynnik_naruszen_id")
private List<IncidentAssessmentFactor> incidentAssessmentFactor;
}
#Data
#Entity
#Table(schema = "odo", name = "czynnik_naruszen_wynik")
public class IncidentAssessmentFactor extends BaseEntity {
#Column(name="komentarz")
private String comment;
#Column(name="czynnik_wybrany")
private Boolean factorIsSelected;
#Column(name = "wartosc_wybrana")
private Float value;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name="ocena_naruszenia_wynik_id", updatable=false, insertable=false)
private IncidentAssessment incidentAssessment;
}
#Data
#Entity
#Table(schema = "odo", name = "ocena_naruszenia_wynik")
public class IncidentAssessment extends BaseEntity {
#Column(name="ocena_naruszenia_id")
private Long incidentAssessmentId;
#Column(name = "wartosc_dotkliwosci_naruszenia")
private Float severityDegreeValue;
My repository:
#Repository
public interface ViolationCriterionRepository extends JpaRepository<ViolationCriterion, Long> {
// #Query("select vc from ViolationCriterion vc inner join vc.violationFactors vf inner join vf.incidentAssessmentFactor iaf inner join iaf.incidentAssessment ia where ia.incidentAssessmentId = ?1 group by vc ")
#Query("select vc from ViolationCriterion vc inner join vc.violationFactors vf inner join vf.incidentAssessmentFactor iaf inner join iaf.incidentAssessment ia where ia.incidentAssessmentId = ?1 group by vc ")
// #Query(value = "select kn.kryterium from odo.d_kryterium_naruszen kn join odo.d_czynnik_naruszen cn on kn.id = cn.id_kryterium_naruszen join odo.czynnik_naruszen_wynik cnw on cnw.czynnik_naruszen_id = cn.id join odo.ocena_naruszenia_wynik onw on cnw.ocena_naruszenia_wynik_id = onw.id where onw.ocena_naruszenia_id = ?1 group by kn.id, cn.id, cnw.id, onw.id", nativeQuery = true)
// #Query(value = "select kn.id, kn.kryterium, kn.data_wpr, kn.opr, cn.id, cn.czynnik, cn.stopien, cn.opr, cn.data_wpr, cnw.id, cnw.data_wpr, cnw.opr, cnw.komentarz, cnw.czynnik_wybrany, cnw.wartosc_wybrana, onw.id, onw.data_wpr, onw.opr, onw.ocena_naruszenia_id, onw.wartosc_dotkliwosci_naruszenia from odo.d_kryterium_naruszen kn join odo.d_czynnik_naruszen cn on kn.id = cn.id_kryterium_naruszen join odo.czynnik_naruszen_wynik cnw on cnw.czynnik_naruszen_id = cn.id join odo.ocena_naruszenia_wynik onw on cnw.ocena_naruszenia_wynik_id = onw.id where onw.ocena_naruszenia_id = ?1 group by kn.id, cn.id, cnw.id, onw.id", nativeQuery = true)
List<ViolationCriterion> findIncidentAssessmentByIncidentAssessmentId(Long incidentId);
// List<ViolationCriterion> findByViolationFactorsIncidentAssessmentFactorIncidentAssessmentIncidentAssessmentIdGroupByViolationCriterionCriterion(Long id);
}
And here I call my repository:
List<ViolationCriterion> violationCriteria = violationCriterionRepository.findIncidentAssessmentByIncidentAssessmentId(id);//vi
In a table czynnik_naruszen_wynik I have 2 different rows because I have 2 rows in table ocena_naruszenia_wynik. The problem is that I have multiple values of entity IncidentAssessmentFactor instead of 1

JPA query for 3 tables

I want to create JPA query for configuring multiple Terminals to one Contract:
CREATE TABLE `contracts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
) ENGINE=InnoDB;
CREATE TABLE `contracts_terminals` (
`terminal_id` int(11) DEFAULT NULL,
`contract_id` int(11) DEFAULT NULL,
) ENGINE=InnoDB;
CREATE TABLE `terminals` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
) ENGINE=InnoDB;
How I can create JPA query which uses table contracts_terminals to assign multiple terminals to one contract?
I use latest MariaDB.
Entities:
Contracts:
#Entity
#Table(name = "contracts")
public class Contracts implements Serializable {
private static final long serialVersionUID = 3873648042962238717L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", unique = true, updatable = false, nullable = false)
private int id;
#Column(length = 255)
private String name;
......
}
Terminals:
#Entity
#Table(name = "terminals")
public class Terminals implements Serializable {
private static final long serialVersionUID = 5288308199642977991L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", unique = true, updatable = false, nullable = false, length = 3)
private int id;
#Column(length = 255)
private String name;
....
}
ContractTerminals:
#Entity
#Table(name = "contract_terminals")
public class ContractTerminals implements Serializable {
private static final long serialVersionUID = 1191148141983861602L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", unique = true, updatable = false, nullable = false)
private int id;
#Column(length = 4)
private Integer terminal_id;
#Column(length = 4)
private Integer contract_id;
....
}

JDBC - two WHERE clause

How I can write a JDBC request with two WHERE clauses.
When I only one WHERE cluse the request is fine.
// example of array
String[] listeId1 = null;
listeId1[0] =['0'];
listeId1[1] =['1'];
String[] listeId = null;
listeId[0] = ['00']
listeId[1] = ['01']
//I don't know how many elements there will be in listeId1 and listeId
String inClause = "?";
int i = 1;
while (i <= listeId.length - 1 ) {
inClause += ",?";
i++;
}
//my request
List<Map<String, Object>> result = this.getJdbcTemplate()
.queryForList("SELECT * FROM TABLE_FONCTION " +
"WHERE ROLE_ID IN (" + inClause + ")" , listeId
+ " AND PROCESSUS_ID IN (" + inClause1 + ")" ,listeId1 )
;
// Definition of my table
CREATE TABLE TABLE_FONCTION (
FONCTION_ID NUMBER(18) NOT NULL,
ACTIVE CHAR(1) NOT NULL,
TYPE_FONCTION_ID NUMBER(18) NOT NULL,
PROCESSUS_ID NUMBER(18) NOT NULL,
ROLE_ID NUMBER(18) NOT NULL
);
What's wrong with my request ?
You never defined inClause1; in particular, before using it to build your query.