Hai all I am currently doing a project for a hospital clinical lab. I have come across a problem while fetching data from database. The problem is as follows.
I have 2 category of tests namely Single test and Profile test. The master table of tests contain both the category of tests.
MASTER TABLE of TESTS(LAB_TEST_SERVICES)
CREATE TABLE LAB_TEST_SERVICES (inttestid bigint identity NOT NULL IDENTITY,
testid varchar(15) NOT NULL, testname varchar(255) NOT NULL, cptdesc varchar(300),
splinstr varchar(300), tstabbr varchar(25), reordertime numeric(15),
tstduration numeric(15), autocancel numeric(15), minbiltime numeric(15),
status int NOT NULL, maxbiltime numeric(15), PRIMARY KEY (inttestid));
The type and category of test is stored in following table
LAB_SERVICES_TYPE
CREATE TABLE LAB_SERVICES_TYPE (inttypeid bigint identity NOT NULL IDENTITY,
inttestid bigint NOT NULL, testtype varchar(25), visitype int NOT NULL,
appgendr char(2) NOT NULL, PRIMARY KEY (inttypeid));
If the test comes under single test category, I need to fill the details to the columns of following tables namely LAB_SPECIMEN_MAPPING,LAB_PARAMETER_MAPPING and LAB_TEST_LOCATION.
LAB_SPECIMEN_MAPPING
CREATE TABLE LAB_SPECIMEN_MAPPING (inttestspcid bigint identity NOT NULL IDENTITY,
inttestid bigint NOT NULL, intspcid bigint NOT NULL, intcontid bigint NOT NULL,
volcol numeric(15, 3) NOT NULL, volreq numeric(15, 3) NOT NULL,
status int NOT NULL, PRIMARY KEY (inttestspcid));
LAB_PARAMETER_MAPPING
CREATE TABLE LAB_PARAMETER_MAPPING (intparaid bigint identity NOT NULL IDENTITY,
inttestid bigint NOT NULL, paraname varchar(255) NOT NULL,
parseq numeric(15, 3) NOT NULL, resulttype varchar(30), shortname varchar(30),
mand int NOT NULL, derived int NOT NULL, status int NOT NULL,
PRIMARY KEY (intparaid));
LAB_TEST_LOCATION
CREATE TABLE LAB_TEST_LOCATION (intlocid bigint identity NOT NULL IDENTITY,
intlabid bigint NOT NULL, inttestid bigint NOT NULL, status int NOT NULL,
PRIMARY KEY (intlocid));
And if the test comes under Profile Test category then I need to fill the details to the columns of following table namely LAB_PROFILE_TEST_LIST. Here for each profile test I am mapping a single test to it.
LAB_PROFILE_TEST_LIST
CREATE TABLE LAB_PROFILE_TEST_LIST (intproftestid int identity NOT NULL IDENTITY,
intprotestid int NOT NULL, intsintestid int NOT NULL, PRIMARY KEY (intproftestid));
I had done the following code to find the name of test which is mapped ie for single test if it is mapped then the testid(inttestid from LAB_TEST_SERVICES) will be inserted in LAB_SPECIMEN_MAPPING,LAB_PARAMETER_MAPPING and LAB_TEST_LOCATION or if the test is profile test the testid(inttestid from LAB_TEST_SERVICES) will be inserted in LAB_PROFILE_TEST_LIST.
The tests which is mapped ( both single & profile test).(My contribution to my problem).
SELECT *
FROM LAB_TEST_SERVICES lts
WHERE EXISTS
(SELECT lsm.inttestid
FROM LAB_SPECIMEN_MAPPING lsm
WHERE lsm.status = 1
AND lts.inttestid = lsm.inttestid)
AND EXISTS
(SELECT ltl.inttestid
FROM LAB_TEST_LOCATION ltl
WHERE ltl.status = 1
AND lts.inttestid = ltl.inttestid)
AND EXISTS
(SELECT lptr.intprotestid
FROM LAB_PROFILE_TEST_LIST lptr WHERE lts.inttestid = lptr.intprotestid)
So when I tried to do this no tests appear because I know that there will be no tests having both the characteristics of Single and Profile tests. I had done so many things but cant find a solution. Kindly help me to find out the details tests which is mapped both single and profile.I am using Java, Hibernate and SQL SERVER. Thanks in advance
Related
I'm new to Java Springboot and I want to join multiple tables.
I have this MySQL schema :
CREATE TABLE `users`
(
`id` int NOT NULL AUTO_INCREMENT,
`email` varchar(128) NOT NULL,
`nickname` varchar(128) NOT NULL,
`password` varchar(256) NOT NULL,CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`),
UNIQUE KEY `nickname` (`nickname`)
);
CREATE TABLE `organizations` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `org_abilities`
(
`id` int NOT NULL AUTO_INCREMENT,
`key` varchar(128) NOT NULL,
`description` varchar(128) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `idx_key` (`key`) USING BTREE
);
CREATE TABLE `org_permissions`
(
`id` int NOT NULL AUTO_INCREMENT,
`id_user` int NOT NULL,
`id_organization` int NOT NULL,
`id_ability` int NOT NULL,
PRIMARY KEY (`id`),
KEY `id_organization` (`id_organization`),
KEY `id_user` (`id_user`),
KEY `users_permissions_ibfk_2` (`id_ability`),
CONSTRAINT `org_permissions_ibfk_0` FOREIGN KEY (`id_organization`) REFERENCES `organizations` (`id`),
CONSTRAINT `org_permissions_ibfk_1` FOREIGN KEY (`id_user`) REFERENCES `users` (`id`),
CONSTRAINT `org_permissions_ibfk_2` FOREIGN KEY (`id_ability`) REFERENCES `org_abilities` (`id`)
);
Where my table org_permissions represent all abilities that a user has within an organization.
I have created the corresponding Java classes. I have a JPA to fetch the datas from the DB to the classes.
I want in my Organization class to have a field Map<long, List<Pair<long, String>>> managers which map an id_user to a list of tuple of abilities where the tuple is (id_ability, org_ability.key).
Finally I use DTO to send my response, and I want my response to look like that :
{
id : _id_organization,
name : "organisation name",
managers : {
id_user: [(id_ability, key), (id_ability, key)],
id_user:[(id_ability, key), (id_ability, key)]
}
}
For example:
SELECT op.*, oa.* FROM org_permissions as op
JOIN org_abilities oa on oa.id = op.id_ability
JOIN organizations o on o.id = op.id_organization
JOIN users u on u.id = op.id_user;
Here, user with id 1 is member of organization 1 and 2. for organization 1 user 1 has the CREATE_EVENTS and DELETE_EVENTS abilities and for organization 2 he only have the DELETE_EVENTS ability.
When getting all the organization I want this result :
[{
id : 1,
name : "Org1",
managers : {
1: [(1, "CREATE_EVENT"), (2,"CREATE_EVENT")]
}
},
{
id : 2,
name : "Org2",
managers : {
1: [(2,"CREATE_EVENT")]
}
}]
Thanks for your help, I'm a bit lost with the High level of springboot and JPA
P.S.: I tried to ask to chat GPT but nothing was concluent
this is my first question here so, please ask if you need more information. I am working on a personal project. I have a relatively complex relational database structure. I create schema.sql on my spring boot project as well as data.sql with sample data. I try to create a web application for simulated fitness centre web pages. I try to display the location name and number of visits for the user. I create a userLocation bean for keeping the result set as a list of the select query. I can test the statement on H2 database and its work. However, on my code, I cannot get the number of visits from the select statement.
Here is my userlocation bean,
#Data
#NoArgsConstructor
public class UserLocation {
private String locName;
private int numOfVisit;
}
Controller class getMapping method
#GetMapping("/secure/userLocation")
public String myLocation(Model model, Authentication authentication) {
String email = authentication.getName();
User currentUser = da.findUserAccount(email);
model.addAttribute("myLocationList", da.getUserLocationList(currentUser.getUserId()));
return "/secure/userLocation";
}
Here database access method;
public List<UserLocation> getUserLocationList(Long userId) {
MapSqlParameterSource namedParameters = new MapSqlParameterSource();
String query = "SELECT l.locName, COUNT(ul.dayOfVisit) FROM location l "
+ "INNER JOIN userLocation ul ON l.locId = ul.locId "
+ "INNER JOIN sec_user sc ON ul.userId = sc.userId "
+ "WHERE sc.userId = :userId AND ul.locId = 1"
+ "GROUP BY l.locName";
namedParameters.addValue("userId", userId);
return jdbc.query(query, namedParameters, new BeanPropertyRowMapper<UserLocation>(UserLocation.class));
}
here schema.sql
CREATE TABLE location (
locId BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
locName VARCHAR(75),
locAddress VARCHAR(255),
locPhone VARCHAR(25),
locEmail VARCHAR(75)
);
CREATE TABLE sec_user (
userId BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(75),
lastName VARCHAR(75),
adress VARCHAR(255),
phone VARCHAR(10),
email VARCHAR(75) NOT NULL UNIQUE,
encryptedPassword VARCHAR(128) NOT NULL,
enabled BIT NOT NULL
);
CREATE TABLE coach (
coachId BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
coachName VARCHAR(75),
coachLevel BIGINT,
coachRating BIGINT,
aboutMe VARCHAR(255)
);
CREATE TABLE fitnessClass (
classId BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
className VARCHAR(75),
classPrice DOUBLE
);
CREATE TABLE generalCert (
certId BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
certName VARCHAR(75)
);
CREATE TABLE certCoach (
certId BIGINT NOT NULL,
coachId BIGINT NOT NULL
);
ALTER TABLE certCoach
ADD CONSTRAINT certCoach_FK1 FOREIGN KEY (certId)
REFERENCES generalCert (certId);
ALTER TABLE certCoach
ADD CONSTRAINT certCoach_FK2 FOREIGN KEY (coachId)
REFERENCES coach (coachId);
CREATE TABLE userLocation (
userLocId BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
locId BIGINT NOT NULL,
userId BIGINT NOT NULL,
isHomeLoc BIT,
dayOfVisit DATE
);
ALTER TABLE userLocation
ADD CONSTRAINT userLocation_FK1 FOREIGN KEY (locId)
REFERENCES location (locId);
ALTER TABLE userLocation
ADD CONSTRAINT userLocation_FK2 FOREIGN KEY (userId)
REFERENCES sec_user (userId);
CREATE TABLE amenity (
amenityId BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
amenityName VARCHAR(75),
locId BIGINT
);
ALTER TABLE amenity
ADD CONSTRAINT amenity_FK FOREIGN KEY (locId)
REFERENCES location (locId);
CREATE TABLE room (
roomId BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
roomName VARCHAR(75),
locId BIGINT
);
ALTER TABLE room
ADD CONSTRAINT room_FK FOREIGN KEY (locId)
REFERENCES location (locId);
CREATE TABLE classCoach (
classId BIGINT NOT NULL,
coachId BIGINT NOT NULL
);
ALTER TABLE classCoach
ADD CONSTRAINT classCoachFK1 FOREIGN KEY (classId)
REFERENCES fitnessClass(classId);
ALTER TABLE classCoach
ADD CONSTRAINT classCoachFK2 FOREIGN KEY (coachId)
REFERENCES coach(coachId);
CREATE TABLE schedule (
ScheduleId BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
ScheduleDate DATE,
ScheduleTime TIME,
RoomId BIGINT,
ClassId BIGINT NOT NULL,
LocId BIGINT NOT NULL
);
ALTER TABLE schedule
ADD CONSTRAINT scheduleFK1 FOREIGN KEY (roomId)
REFERENCES room(RoomId);
ALTER TABLE schedule
ADD CONSTRAINT scheduleFK2 FOREIGN KEY (classId)
REFERENCES fitnessClass(classId);
ALTER TABLE schedule
ADD CONSTRAINT ScheduleFK3 FOREIGN KEY (LocId)
REFERENCES location(LocId);
CREATE TABLE reservation (
ClassId BIGINT NOT NULL,
userId BIGINT NOT NULL
);
ALTER TABLE reservation
ADD CONSTRAINT reservationFK1 FOREIGN KEY (classId)
REFERENCES fitnessClass(classId);
ALTER TABLE reservation
ADD CONSTRAINT reservationFK2 FOREIGN KEY (userId)
REFERENCES sec_user(userId);
CREATE TABLE workFrom (
coachId BIGINT NOT NULL,
locId BIGINT NOT NULL
);
ALTER TABLE workFrom
ADD CONSTRAINT workFromFK1 FOREIGN KEY (coachId)
REFERENCES coach(coachId);
ALTER TABLE workFrom
ADD CONSTRAINT workFromFK2 FOREIGN KEY (locId)
REFERENCES location(locId);
CREATE TABLE review (
ReviewId BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
CoachId BIGINT NOT NULL,
userId BIGINT NOT NULL,
ReviewDate DATE,
ComScore CHAR(1),
EnthScore CHAR(1),
PunctScore CHAR(1),
ReviewText VARCHAR(500)
);
ALTER TABLE review
ADD CONSTRAINT reviewFK1 FOREIGN KEY (coachId)
REFERENCES coach(coachId);
ALTER TABLE review
ADD CONSTRAINT reviewFK2 FOREIGN KEY (userId)
REFERENCES sec_user(userId);
CREATE TABLE Reference (
CoachId BIGINT NOT NULL,
userId BIGINT NOT NULL
);
ALTER TABLE Reference
ADD CONSTRAINT ReferenceFK1 FOREIGN KEY (coachId)
REFERENCES coach(coachId);
ALTER TABLE review
ADD CONSTRAINT ReferenceFK2 FOREIGN KEY (userId)
REFERENCES sec_user(userId);
CREATE TABLE ClientCoach (
coachId BIGINT NOT NULL,
userId BIGINT NOT NULL,
myCoach BIT
);
ALTER TABLE ClientCoach
ADD CONSTRAINT ClientCoachFK1 FOREIGN KEY (coachId)
REFERENCES coach(coachId);
ALTER TABLE ClientCoach
ADD CONSTRAINT ClientCoachFK2 FOREIGN KEY (userId)
REFERENCES sec_user(userId);
CREATE TABLE sec_role(
roleId BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
roleName VARCHAR(30) NOT NULL UNIQUE
);
CREATE TABLE user_role
(
id BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
userId BIGINT NOT NULL,
roleId BIGINT NOT NULL
);
ALTER TABLE user_role
ADD CONSTRAINT user_role_uk UNIQUE (userId, roleId);
ALTER TABLE user_role
ADD CONSTRAINT user_role_fk1 FOREIGN KEY (userId)
REFERENCES sec_user (userId);
ALTER TABLE user_role
ADD CONSTRAINT user_role_fk2 FOREIGN KEY (roleId)
REFERENCES sec_role (roleId);
Here the result web page
Here is EERD for the schema
Please try:
SELECT l.locName, COUNT(ul.dayOfVisit) AS numOfVisit -- ...
(to alias numOfVisit), since we are using a BeanPropertyRowMapper (which mapps by "bean properties" (i.e. "field names"): https://www.google.com/search?q=java+bean+naming+conventions).
Alternatively use an other/custom RowMapper.
And since even javadoc recommends:
... For best performance, consider using a custom RowMapper implementation.
Best:
return jdbc.query(query, namedParameters,
(ResultSet rs, int rowNum) -> { // one ResultSet per row:
// column indices start with 1(!):
return new UserLocation(rs.getString(1), rs.getInt(2));
// alternatively (name based): rs.getString("locName")...
}
);
;)
RowMapper javadoc (spring-jdbc:current)
ResultSet javadoc (jdk17)
and since RowMapper is a/meets the requirements of a functional interface, we can write it as lambda expression.
Is there a way to retrieve the list of distribution column(s) info from the Azure Synapse JDBC drivers? I can do most of it but stuck on the WITH DISTRIBUTION WITH clause(s) part at the bottom.
For example, I just need something basic to re-create a DDL like so:
IF EXISTS(SELECT 1 FROM sys.objects WHERE [type]='U' AND [name] = 'AZURE_TEST'
AND SCHEMA_NAME(schema_id) = 'dbo')
DROP TABLE [dbo].[AZURE_TEST]
GO
CREATE TABLE [dbo].[AZURE_TEST] (
BIGINT1 BIGINT NOT NULL,
BOOLEAN1 BIT NOT NULL,
BYTEINT1 TINYINT NOT NULL PRIMARY KEY NONCLUSTERED NOT ENFORCED,
CHAR1 CHAR(1) NULL,
CHAR2 CHAR(10) NULL,
CHARACTER_VARYING1 VARCHAR(10) NULL,
CHARACTER1 CHAR(1) NOT NULL,
CHARACTER2 CHAR(10) NULL,
DATE1 DATE NULL,
DOUBLE_PRECISION1 FLOAT(15) NULL,
INTEGER1 INTEGER NULL,
INTERVAL1 VARCHAR(50) NULL,
NATIONAL_CHARACTER_VARYING2 NVARCHAR(10) NULL,
NUMERIC1 NUMERIC(18, 0) NULL,
NUMERIC2 NUMERIC(10, 0) NOT NULL,
NUMERIC3 NUMERIC(10, 2) NULL,
REAL1 REAL NULL,
SMALLINT1 SMALLINT NULL,
TIME1 TIME NULL,
TIMESTAMP1 DATETIME2 NULL
)
WITH
(
DISTRIBUTION = HASH ( [BIGINT1] ),
CLUSTERED COLUMNSTORE INDEX
)
GO
You can retrieve the columns used for the DISTRIBUTION for a given table by running the next sql:
SELECT c.name FROM sys.columns AS c
INNER JOIN sys.tables AS t ON t.object_id = c.object_id
INNER JOIN sys.schemas AS s ON s.schema_id = t.schema_id
INNER JOIN sys.pdw_column_distribution_properties AS d ON t.object_id = d.object_id AND d.column_id = c.column_id
WHERE t.name = 'table_name' AND s.name = 'schema_name' AND d.distribution_ordinal <> 0;
I have two tables as follows:
table1:
CREATE TABLE `Product` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`typename` varchar(255) DEFAULT NULL,
`typecode` varchar(55) DEFAULT NULL,
) ENGINE=InnoDB AUTO_INCREMENT=396 DEFAULT CHARSET=latin1;
table2:
CREATE TABLE measurements (
id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
age_group varchar(20) NOT NULL,
articleType NOT NULL,
dimension text ,
createdOn int(11) NOT NULL,
updatedOn int(11) NOT NULL,
createdBy text NOT NULL,
)ENGINE=InnoDB AUTO_INCREMENT=396 DEFAULT CHARSET=latin1;
Now how can I join the two tables with join column measurements.articleType = product.typename in Java Persistence.
I know the concept of using one to many and many to one using foreign key(http://en.wikibooks.org/wiki/Java_Persistence/OneToMany). But the above tables does not have foreign key.
I'm here assuming you want a Many-to-Many.
In java, if you want it to be bidirectional, use a
#ManyToMany(mappedBy = "products")
public List<Product> getProducts() { ... }
and in Product
#ManyToMany
#JoinTable(name = "product_measurement")
public List<Measurement> getMeasurement() { ... }
In sql it will be :
CREATE TABLE product_measurement
(
product_measurement_id int(11) NOT NULL,
measurement_product_id int(11) NOT NULL,
FOREIGN KEY (measurement_product_id) REFERENCES measurement (id),
FOREIGN KEY (product_measurement) REFERENCES product (id)
);
You could use JPQL or HQL Native SQL to achieve that. To use Query or Named Query you need to associate the entities together.
Since it is not possible in your case, the Native SQL is the only option.
But consider creating constraints between tables to preserve the data integrity.
I have two tables, A and B. When inserting a new row into table B, how do I insert a FK as a reference to a record in table A?
I've got the two below tables:
--
-- Table structure for table `sector`
--
CREATE TABLE IF NOT EXISTS `sector` (
`sector_id` int(11) NOT NULL AUTO_INCREMENT,
`sector_name` varchar(100) NOT NULL,
`sector_url` varchar(500) NOT NULL,
PRIMARY KEY (`sector_id`),
UNIQUE KEY `sector_id` (`sector_id`,`sector_name`,`sector_url`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `constituent` (
`constituent_id` int(11) NOT NULL AUTO_INCREMENT,
`constituent_name` varchar(100) DEFAULT '',
`constituent_ticker` varchar(10) NOT NULL,
`constituent_isin_number` varchar(50) DEFAULT '',
`constituent_currency` varchar(10) DEFAULT '',
`sector_id` int(11) NOT NULL,
PRIMARY KEY (`constituent_id`),
KEY `sector_id` (`sector_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- Constraints for table `constituent`
--
ALTER TABLE `constituent`
ADD CONSTRAINT `constituent_ibfk_1` FOREIGN KEY (`sector_id`) REFERENCES `sector` (`sector_id`);
When I do an insert, how can I structure the query such that when I insert into the table 'constituent', I'm using the primary key of 'sector'?
INSERT into constituent (constituent_name, constituent_ticker, constituent_isin_number, constituent_currency, sectorFK)
values ("the name", "the ticker", "the number", "the currency", "the foreign key???")
To be able to get a primary key value after inserting into table B, in order to insert it into the table A, you could use last_insert_id() function, which when used without a parameter returns a last automatically generated value that was set for an AUTO_INCREMENT column:
For example:
insert into B(col)
values(1);
insert into A(t1_id, col)
values(last_insert_id(), 2);
insert into A(t1_id, col)
values(last_insert_id(), 3);
SQLFIddle Demo
Assuming there is a sector with sector_name 'sector 1' you could do something like this.
INSERT into constituent (constituent_name, constituent_ticker, constituent_isin_number, constituent_currency, sector_id) (select 'the name', 'the ticker', 'the number', 'the currency', sector_id from sector where sector_name = "sector 1");