error while mapping database schema - subsonic

When I try to map with subsonic 3.0.0.3 database, i get error:
"Running transformation: System.InvalidOperationException: Sequence contains more than one matching element..."
Where i should look for error?

SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL';
CREATE SCHEMA IF NOT EXISTS osm2 DEFAULT CHARACTER SET cp1251 COLLATE cp1251_general_ci;
USE osm2;
-- Table mydb.sw_profile
CREATE TABLE IF NOT EXISTS osm2.sw_profile (
id INT NOT NULL ,
name VARCHAR(45) NOT NULL ,
configuration VARCHAR(500) NOT NULL ,
comments VARCHAR(45) NULL ,
PRIMARY KEY (id) )
ENGINE = InnoDB;
-- Table mydb.sw_type
CREATE TABLE IF NOT EXISTS osm2.sw_type(
id INT NOT NULL,
name VARCHAR (45) NOT NULL,
ports_num INT NOT NULL,
trunc_ports VARCHAR (45) NOT NULL,
supports_dhcp TINYINT (1) NOT NULL,
PRIMARY KEY (id)
)
ENGINE = INNODB;
-- Table mydb.sw
CREATE TABLE IF NOT EXISTS osm2.sw(
id INT NOT NULL,
sn VARCHAR (45) NULL,
mac VARCHAR (45) NOT NULL,
ip VARCHAR (45) NOT NULL,
comments VARCHAR (45) NULL,
sw_profile_id INT NOT NULL,
sw_type_id INT NOT NULL,
PRIMARY KEY (id),
INDEX fk_sw_sw_profile (sw_profile_id ASC),
INDEX fk_sw_sw_type1 (sw_type_id ASC),
CONSTRAINT fk_sw_sw_profile
FOREIGN KEY (sw_profile_id)
REFERENCES mydb.sw_profile (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT fk_sw_sw_type1
FOREIGN KEY (sw_type_id)
REFERENCES mydb.sw_type (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
ENGINE = INNODB
DEFAULT CHARACTER SET = cp1251;
-- Table mydb.port
CREATE TABLE IF NOT EXISTS osm2.port(
id INT NOT NULL,
name VARCHAR (45) NOT NULL,
state TINYINT (1) NOT NULL,
user_id INT NULL,
sw_id INT NOT NULL,
PRIMARY KEY (id),
INDEX fk_port_sw1 (sw_id ASC),
CONSTRAINT fk_port_sw1
FOREIGN KEY (sw_id)
REFERENCES mydb.sw (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
ENGINE = INNODB;
-- Table mydb.vlan
CREATE TABLE IF NOT EXISTS osm2.vlan(
id INT NOT NULL,
name VARCHAR (45) NOT NULL,
tag VARCHAR (45) NOT NULL,
comments VARCHAR (500) NULL,
PRIMARY KEY (id)
)
ENGINE = INNODB;
-- Table mydb.address
CREATE TABLE IF NOT EXISTS osm2.address(
id INT NOT NULL,
name VARCHAR (45) NOT NULL,
short_name VARCHAR (45) NOT NULL,
comments VARCHAR (45) NULL,
sw_id INT NOT NULL,
PRIMARY KEY (id),
INDEX fk_address_sw1 (sw_id ASC),
CONSTRAINT fk_address_sw1
FOREIGN KEY (sw_id)
REFERENCES mydb.sw (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
ENGINE = INNODB;
-- Table mydb.tariff
CREATE TABLE IF NOT EXISTS osm2.tariff(
id INT NOT NULL,
name VARCHAR (45) NOT NULL,
price DOUBLE NOT NULL,
speed VARCHAR (45) NOT NULL,
PRIMARY KEY (id)
)
ENGINE = INNODB;
-- Table mydb.client
CREATE TABLE IF NOT EXISTS osm2.client(
id INT NOT NULL,
utm_id VARCHAR (45) NULL,
utm_login VARCHAR (45) NULL,
ip VARCHAR (45) NOT NULL,
ip_second VARCHAR (45) NULL,
contacts VARCHAR (500) NULL,
comments VARCHAR (500) NULL,
act VARCHAR (500) NULL,
vlan_id INT NOT NULL,
address_id INT NOT NULL,
tariff_id INT NOT NULL,
PRIMARY KEY (id),
INDEX fk_client_vlan1 (vlan_id ASC),
INDEX fk_client_address1 (address_id ASC),
INDEX fk_client_tariff1 (tariff_id ASC),
CONSTRAINT fk_client_vlan1
FOREIGN KEY (vlan_id)
REFERENCES mydb.vlan (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT fk_client_address1
FOREIGN KEY (address_id)
REFERENCES mydb.address (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT fk_client_tariff1
FOREIGN KEY (tariff_id)
REFERENCES mydb.tariff (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
ENGINE = INNODB;
-- Table mydb.port_has_vlan
CREATE TABLE IF NOT EXISTS osm2.port_has_vlan(
port_id INT NOT NULL,
vlan_id INT NOT NULL,
PRIMARY KEY (port_id, vlan_id),
INDEX fk_port_has_vlan_port1 (port_id ASC),
INDEX fk_port_has_vlan_vlan1 (vlan_id ASC),
CONSTRAINT fk_port_has_vlan_port1
FOREIGN KEY (port_id)
REFERENCES mydb.port (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT fk_port_has_vlan_vlan1
FOREIGN KEY (vlan_id)
REFERENCES mydb.vlan (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
ENGINE = INNODB;
-- Table mydb.request_state
CREATE TABLE IF NOT EXISTS osm2.request_state(
id INT NOT NULL,
name VARCHAR (45) NOT NULL,
PRIMARY KEY (id)
)
ENGINE = INNODB;
-- Table mydb.request_type
CREATE TABLE IF NOT EXISTS osm2.request_type(
id INT NOT NULL,
name VARCHAR (45) NOT NULL,
comments VARCHAR (500) NULL,
PRIMARY KEY (id)
)
ENGINE = INNODB;
-- Table mydb.request
CREATE TABLE IF NOT EXISTS osm2.request(
id INT NOT NULL,
date DATETIME NOT NULL,
comments VARCHAR (500) NULL,
log VARCHAR (500) NULL,
request_state_id INT NOT NULL,
request_type_id INT NOT NULL,
client_id INT NOT NULL,
PRIMARY KEY (id),
INDEX fk_request_request_state1 (request_state_id ASC),
INDEX fk_request_request_type1 (request_type_id ASC),
INDEX fk_request_client1 (client_id ASC),
CONSTRAINT fk_request_request_state1
FOREIGN KEY (request_state_id)
REFERENCES mydb.request_state (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT fk_request_request_type1
FOREIGN KEY (request_type_id)
REFERENCES mydb.request_type (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT fk_request_client1
FOREIGN KEY (client_id)
REFERENCES mydb.client (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
ENGINE = INNODB;
-- Table mydb.department
CREATE TABLE IF NOT EXISTS osm2.department(
id INT NOT NULL,
name VARCHAR (45) NOT NULL,
comments VARCHAR (45) NOT NULL,
PRIMARY KEY (id)
)
ENGINE = INNODB;
-- Table mydb.group
CREATE TABLE IF NOT EXISTS osm2.group(
id INT NOT NULL,
name VARCHAR (45) NOT NULL,
PRIMARY KEY (id)
)
ENGINE = INNODB;
-- Table mydb.account
CREATE TABLE IF NOT EXISTS osm2.account(
id INT NOT NULL,
login VARCHAR (45) NOT NULL,
password VARCHAR (45) NOT NULL,
group_id INT NOT NULL,
PRIMARY KEY (id),
INDEX fk_account_group1 (group_id ASC),
CONSTRAINT fk_account_group1
FOREIGN KEY (group_id)
REFERENCES mydb.group (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
ENGINE = INNODB;
-- Table mydb.staff
CREATE TABLE IF NOT EXISTS osm2.staff(
id INT NOT NULL,
name VARCHAR (45) NOT NULL,
contacts VARCHAR (45) NOT NULL,
department_id INT NOT NULL,
account_id INT NOT NULL,
PRIMARY KEY (id),
INDEX fk_staff_department1 (department_id ASC),
INDEX fk_staff_account1 (account_id ASC),
CONSTRAINT fk_staff_department1
FOREIGN KEY (department_id)
REFERENCES mydb.department (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT fk_staff_account1
FOREIGN KEY (account_id)
REFERENCES mydb.account (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
ENGINE = INNODB;
-- Table mydb.fid
CREATE TABLE IF NOT EXISTS osm2.fid(
id INT NOT NULL,
text VARCHAR (500) NOT NULL,
comments VARCHAR (500) NULL,
PRIMARY KEY (id)
)
ENGINE = INNODB;
-- Table mydb.group_has_fid
CREATE TABLE IF NOT EXISTS osm2.group_has_fid(
group_id INT NOT NULL,
fid_id INT NOT NULL,
PRIMARY KEY (group_id, fid_id),
INDEX fk_group_has_fid_group1 (group_id ASC),
INDEX fk_group_has_fid_fid1 (fid_id ASC),
CONSTRAINT fk_group_has_fid_group1
FOREIGN KEY (group_id)
REFERENCES mydb.group (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT fk_group_has_fid_fid1
FOREIGN KEY (fid_id)
REFERENCES mydb.fid (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
ENGINE = INNODB;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;

It looks like I found problem.
There are some tables with 2 fields with property primary key (through this tables uses connection many to many) in my schema.
Is it bug?

Related

Import Export data from a CSV file to SQL Server DB?

I am working on a web application where i have to do a import export functionality. i am new in this so i want your suggestions and there are some issues that i am facing to do this functionality,
So first i have a JSON array from Frontend (AngularJs)
[
{
"MyName": "Shubham",
"UserType": "Premium",
"DialCode": "India",
"ContactNumber": "9876543210",
"EmailAddress": "Contact#Shubh.com"
"Country": "India",
"Notes": "Notes-Notes-Notes-Notes"
},
{
"MyName": "Shubham 2",
"UserType": "Free Trial",
"DialCode": "India",
"ContactNumber": "123456789",
"EmailAddress": "Contact2#Shubh.com"
"Country": "India",
"Notes": "Notes-Notes-Notes-Notes"
} ]
Now i am converting this array to a XML in NodeJs Using XMLbuilder
Like This
<UserXML>
<MyName>Shubham</MyName>
<UserType>Premium</UserType>
<DialCode>India</DialCode>
<ContactNumber>9876543210</ContactNumber>
<EmailAddress>Contact#Shubh.com</EmailAddress>
<Country>India</Country>
<Notes>Notes-Notes-Notes-Notes</Notes>
</UserXML>
<UserXML>
<MyName>Shubham 2</MyName>
<UserType>Free Trial</UserType>
<DialCode>India</DialCode>
<ContactNumber>123456789</ContactNumber>
<EmailAddress>Contact2#Shubh.com</EmailAddress>
<Country>India</Country>
<Notes>Notes2-Notes2-Notes2-Notes2</Notes>
</UserXML>
Now i am using this XML in SQL Server to insert these 2 records into my user table
now the issue is i have another table where country code and country name is saved i am using Foreign Key ref in my user table
i have made a sample code
DROP TABLE IF EXISTS #Country
DROP TABLE IF EXISTS #user
DROP TABLE IF EXISTS #UserType
CREATE TABLE #Country
(
Id INT PRIMARY KEY identity(1 ,1),
Name VARCHAR(50) NOT NULL,
DialCode VARCHAR(50) NOT NULL
)
CREATE TABLE #UserType
(
Id INT PRIMARY KEY identity(1 ,1),
Name VARCHAR(50) NOT NULL
)
CREATE TABLE #user
(
Id INT PRIMARY KEY IDENTITY(1 ,1),
Name VARCHAR(50) NOT NULL,
UserTypeId INT NOT NULL,
DialCodeId INT NOT NULL,
ContactNumber VARCHAR(50) NOT NULL,
EmailAddress VARCHAR(50) NOT NULL,
CountryId INT NOT NULL,
Notes VARCHAR(50) NOT NULL
FOREIGN KEY(CountryId) REFERENCES #Country(Id),
FOREIGN KEY(UserTypeId) REFERENCES #UserType(Id)
);
INSERT INTO #Country (Name,DialCode)
VALUES ('India','+91'),
('Dubai','+971'),
('U.S','+1') ;
INSERT INTO #UserType (Name)
VALUES ('Premium'),
('Free Trial');
CASE 1 (Working Fine) if i have a single record then there is no issue by using this apporch
declare #xml xml = '<UserXML>
<Name>Shubham CASE-1</Name>
<UserType>Premium</UserType>
<DialCode>India</DialCode>
<ContactNumber>9876543210</ContactNumber>
<EmailAddress>Contact#Shubh.com</EmailAddress>
<Country>India</Country>
<Notes>Notes-Notes-Notes-Notes CASE-1</Notes>
</UserXML>'
Now i have to check the country name/User Type and match it with the country table to get the id
DECLARE #CountryId INT
,#UserType INT
SELECT #CountryId = id FROM #Country WHERE Name LIKE ''+(select U.Items.value('./DialCode[1]','NVARCHAR(200)') as DialCode FROM #xml.nodes('/UserXML') U(Items))+'%'
SELECT #UserType = id FROM #UserType WHERE Name LIKE ''+(select U.Items.value('./UserType[1]','NVARCHAR(200)') as UserType FROM #xml.nodes('/UserXML') U(Items))+'%'
INSERT INTO #user
SELECT
U.Item.query('./Name').value('.','VARCHAR(100)') Name,
#UserType,
#CountryId,
U.Item.query('./ContactNumber').value('.','VARCHAR(100)') ContactNumber,
U.Item.query('./EmailAddress').value('.','VARCHAR(100)') EmailAddress,
#CountryId,
U.Item.query('./Notes').value('.','VARCHAR(100)') Notes
FROM #Xml.nodes('/UserXML') AS U(Item)
CASE-2 (Well the Isssue is here) if i have multiple records then how can i check every node and then make a join or something like that to make my insert query work fine
declare #xml2 xml = '<UserXML>
<Name>Shubham CASE-2</Name>
<UserType>Premium</UserType>
<DialCode>India</DialCode>
<ContactNumber>9876543210</ContactNumber>
<EmailAddress>Contact#Shubh.com</EmailAddress>
<Country>India</Country>
<Notes>Notes-Notes-Notes-Notes CASE-2</Notes>
</UserXML>
<UserXML>
<Name>Shubham 2 CASE-2</Name>
<UserType>Free Trial</UserType>
<DialCode>Dubai</DialCode>
<ContactNumber>123456789</ContactNumber>
<EmailAddress>Contact2#Shubh.com</EmailAddress>
<Country>Dubai</Country>
<Notes>Notes2-Notes2-Notes2-Notes2 CASE-2</Notes>
</UserXML>'
DECLARE #CountryId2 INT
,#UserType2 INT
SELECT #CountryId2 = id FROM #Country WHERE Name LIKE ''+(select U.Items.value('./DialCode[1]','NVARCHAR(200)') as DialCode FROM #xml2.nodes('/UserXML') U(Items))+'%'
SELECT #UserType2 = id FROM #UserType WHERE Name LIKE ''+(select U.Items.value('./UserType[1]','NVARCHAR(200)') as UserType FROM #xml2.nodes('/UserXML') U(Items))+'%'
INSERT INTO #user
SELECT
U.Item.query('./Name').value('.','VARCHAR(100)') Name,
#UserType,
#CountryId,
U.Item.query('./ContactNumber').value('.','VARCHAR(100)') ContactNumber,
-- U.Item.query('./EmailAddress').value('.','VARCHAR(100)') EmailAddress,
#CountryId,
U.Item.query('./Notes').value('.','VARCHAR(100)') Notes
FROM #xml2.nodes('/UserXML') AS U(Item)
Please If you have any suggestions Or any other better approach for doing this task then help me out i am new to this so i don't know about the best approach for doing this task
You can read JSON directly and perform the JOIN
SELECT entity.*
FROM OPENROWSET (BULK N'd:\temp\file.json', SINGLE_CLOB) as j
CROSS APPLY OPENJSON(BulkColumn)
WITH(
MyName nvarchar(100)
,UserType nvarchar(100)
,DialCode nvarchar(100)
,ContactNumber nvarchar(100)
,EmailAddress nvarchar(100)
,Country nvarchar(100)
,Notes nvarchar(500)
) AS entity
More infos about import JSON documents and the OPENJSON

How to join table that contains no data yet with sqlite

I am trying to join two tables: users and favourites. There is a possibility that a user has no favourites yet and when I tried to INNER JOIN the two I didn't get back the user without any favourites. Is there any way to join even if the second table has no data for that user?
I created the users tabel with the following code:
db.run(`CREATE TABLE Users(
UserId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
Name TEXT NOT NULL,
Password TEXT NOT NULL,
Phone VARCHAR,
Email TEXT,
RestaurantId INTEGER,
FOREIGN KEY(RestaurantId) REFERENCES Restaurants(RestaurantId))`, (err) => {
if(err) {
console.error(err.message);
} else {
//insert some values
var insert = 'INSERT INTO Users (Name, Password, Phone, Email, RestaurantId) VALUES (?, ?, ?, ?, ?)';
db.run(insert, [
'Liam',
'blabla',
'+32412345678',
'email#email.com',
1
]);
}
}
);
And the favourites table with:
db.run(`CREATE TABLE Favourites(
FavouriteId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
UserId INTEGER NOT NULL,
RestaurantId INTEGER NOT NULL,
FOREIGN KEY(UserId) REFERENCES Users(UserId),
FOREIGN KEY(RestaurantId) REFERENCES Restaurants(RestaurantId))`, (err) => {
if(err) {
console.error(err.message);
} else {
//insert some values
var insert = 'INSERT INTO Favourites (UserId, RestaurantId) VALUES (?, ?)';
db.run(insert, [
1,
1
]);
}
}
);
There is no problem with the data that exists in the table that was generated after these inserts. The problem only exists when a new user without favourites gets added to the database.
You are looking for LEFT JOIN. Take a look at the documentation: https://www.w3resource.com/sqlite/sqlite-left-join.php.
LEFT JOIN returns all the records on the left side of the join, with the matched records from the right side.

AzureMobileClient DatabaseFirst manually create datatable fail?

I try to user AzureMobileClient in my XamarinForm with Database First model. For now I do not use offline sync.
So I use this script to create the table in my AZURE SQL DB:
CREATE TABLE [dbo].[TodoItems] (
-- This must be a string suitable for a GUID
[Id] NVARCHAR (128) NOT NULL,
-- These are the system properties
[Version] ROWVERSION NOT NULL,
[CreatedAt] DATETIMEOFFSET (7) NOT NULL,
[UpdatedAt] DATETIMEOFFSET (7) NULL,
[Deleted] BIT NOT NULL,
-- These are the properties of our DTO not included in EntityFramework
[Text] NVARCHAR (MAX) NULL,
[Complete] BIT NOT NULL,
);
CREATE CLUSTERED INDEX [IX_CreatedAt]
ON [dbo].TodoItems([CreatedAt] ASC);
ALTER TABLE [dbo].[TodoItems]
ADD CONSTRAINT [PK_dbo.TodoItems] PRIMARY KEY NONCLUSTERED ([Id] ASC);
CREATE TRIGGER [TR_dbo_TodoItems_InsertUpdateDelete] ON [dbo].[TodoItems]
AFTER INSERT, UPDATE, DELETE AS
BEGIN
UPDATE [dbo].[TodoItems]
SET [dbo].[TodoItems].[UpdatedAt] = CONVERT(DATETIMEOFFSET,
SYSUTCDATETIME())
FROM INSERTED WHERE inserted.[Id] = [dbo].[TodoItems].[Id]
END;
Based on the sample TodoItem provided by Azure. I can do a GetAllItems without any bug (the table is empty for now). But when I try to insert a item I got this error on my Azure backend:
{[Message, The operation failed with the following error: 'Cannot insert the value NULL into column 'CreatedAt', table 'TechCenterCentaur.dbo.TodoItems'; column does not allow nulls. INSERT fails.The statement has been terminated.'.]}
Normally Azure is supposed to take care of that automatically?
I just do that in my XF code:
TodoItem cl = new TodoItem();
cl.Name = "Test";
await _todoTable.InsertAsync(cl);
The call is well made to the backend with a TodoItem containing only Test and all the other fields are null. The exception occurred in the backend :
public async Task<IHttpActionResult> PostTodoItem(TodoItem item)
{
try
{
TodoItem current = await InsertAsync(item); //crash here
return CreatedAtRoute("Tables", new { id = current.Id }, current);
}
catch (System.Exception e)
{
throw;
}
}
Any suggestion?
Ok I found the solution. The problem was in my SQL table. I was missing the 2 ALTER TABLE for new GUID for ID and the CreatedDate.
Here my new script:
USE [TechCenterCentaur]
GO
/****** Object: Table [dbo].[TodoItems] Script Date: 2017-11-08 11:09:14
******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TodoItems](
[Id] [nvarchar](128) NOT NULL,
[Text] [nvarchar](max) NULL,
[Complete] [bit] NOT NULL,
[Version] [timestamp] NOT NULL,
[CreatedAt] [datetimeoffset](7) NOT NULL,
[UpdatedAt] [datetimeoffset](7) NULL,
[Deleted] [bit] NOT NULL,
CONSTRAINT [PK_dbo.TodoItems] PRIMARY KEY NONCLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)
GO
ALTER TABLE [dbo].[TodoItems] ADD DEFAULT (newid()) FOR [Id]
GO
ALTER TABLE [dbo].[TodoItems] ADD DEFAULT (sysutcdatetime()) FOR
[CreatedAt]
GO
CREATE TRIGGER [TR_dbo_TodoItems_InsertUpdateDelete] ON [dbo].[TodoItems]
AFTER INSERT, UPDATE, DELETE AS
BEGIN
UPDATE [dbo].[TodoItems]
SET [dbo].[TodoItems].[UpdatedAt] = CONVERT(DATETIMEOFFSET,
SYSUTCDATETIME())
FROM INSERTED WHERE inserted.[Id] = [dbo].[TodoItems].[Id]
END;
GO

Mybatis nested one-to-one or one-to-many relations mapping

I use myBatis to map a simple database (as an example).
It consists of 4 models: User, Car, Tariff, Insurance.
User has private List carList and private Tariff tariff and some other fields with getters and setters.
Car has private Insurance insurance and some other fields with getters and setters.
So I can map only 1st nesting level. I mean i can map User and its fields - Tariff and a List of Cars. But I can't map Insurance field of Car. What should I do?
Here is my mapper.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace = "UserNamespace">
<resultMap id="resultUser" type="User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<association property="tariff" column="tariff" select="getTariff" javaType="Tariff"/>
<collection property="carList" column="id" select="getCars" javaType="ArrayList" ofType="Car">
<id property="id" column="id"/>
<result property="model" column="model"/>
<association property="insurance" column="insurance" select="getInsurance" javaType="Insurance"/>
</collection>
</resultMap>
<select id = "getAll" resultMap = "resultUser">
SELECT * FROM carwashservice.users
</select>
<select id = "getTariff" parameterType="int" resultType="Tariff">
SELECT tariffs.description FROM carwashservice.tariffs WHERE tariffs.id = #{id}
</select>
<select id = "getCars" parameterType="int" resultType="Car">
SELECT * FROM carwashservice.cars WHERE cars.user = #{id}
</select>
<select id = "getInsurance" parameterType="int" resultType="Insurance">
SELECT * FROM carwashservice.insurance WHERE insurance.id = #{insurance}
</select>
</mapper>
And my DB:
CREATE DATABASE IF NOT EXISTS `carwashservice` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `carwashservice`;
DROP TABLE IF EXISTS `cars`;
CREATE TABLE `cars` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`model` VARCHAR(45) NOT NULL,
`user` INT(11) DEFAULT NULL,
`insurance` INT(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `user_idx` (`user`),
KEY `insurance_idx` (`insurance`),
CONSTRAINT `user` FOREIGN KEY (`user`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `insurance`;
CREATE TABLE `insurance` (
`id` INT(11) NOT NULL,
`cost` VARCHAR(45) NOT NULL,
`exp_date` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `id` FOREIGN KEY (`id`) REFERENCES `cars` (`insurance`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `tariffs`;
CREATE TABLE `tariffs` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`description` VARCHAR(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `id` (`id`,`description`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` INT(11) NOT NULL,
`name` VARCHAR(45) NOT NULL,
`tariff` INT(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `tariff_idx` (`tariff`),
KEY `id` (`id`,`name`),
CONSTRAINT `tariff` FOREIGN KEY (`tariff`) REFERENCES `tariffs` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
You should extract the car mapping:
<collection property="carList" column="id" select="getCars" javaType="ArrayList" ofType="Car" />
In a separated resultMap:
<resultMap id="resultCar" type="Car">
<id property="id" column="id"/>
<result property="model" column="model"/>
<association property="insurance" column="insurance" select="getInsurance" javaType="Insurance"/>
</resultMap>
And reference it from the statement
<select id = "getCars" parameterType="int" resultMap="resultCar">
You are using resultType="Car". This is fine for basic mapping, but there is an association with Insurance: this is not basic and require specific mapping.
Furthermore, the getCars statement uses its own resultMap, then what you define inside carList collection is actually ignored (out of scope). that's why the insurance list is null.

Nodejs Sequelize.sync() hanging on SHOW INDEX?

When restating our azure server the equalise.sync() method is hanging on the SHOW INDEX of a table it has just created. Even though the table is almost identical to one just created.
The model for our relation 'Teachers' is as follows:
'use strict';
module.exports = function(sequelize, DataTypes) {
var Teacher = sequelize.define('Teacher', {
email: DataTypes.STRING
} , {
classMethods: {
associate: function(models) {
// associations can be defined here
}
}
});
return Teacher;
};
And this is the code from a student relation that was successfully created, proceeds past SHOW INDEX and does not cause the script to hang:
'use strict';
module.exports = function(sequelize, DataTypes) {
var Student = sequelize.define('Student', {
email: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
}
}
});
return Student;
};
And this is where the code gets up to before hanging/crashing:
d-i89-237-11:IoTSchool-Backend mitchell$ npm start
> express-example#0.0.0 start /Users/mitchell/Documents/deco3801/IoTSchool-Backend
> node ./bin/www
Executing (default): CREATE TABLE IF NOT EXISTS `Events` (`id` INTEGER auto_increment , `ename` VARCHAR(255), `edata` VARCHAR(255), `type` INTEGER, `time` VARCHAR(255), `deviceid` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `Events` FROM `IoTSchool`
Executing (default): CREATE TABLE IF NOT EXISTS `Schools` (`id` INTEGER NOT NULL auto_increment , `name` VARCHAR(255), `email` VARCHAR(255), `password` VARCHAR(255), `accessToken` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `Schools` FROM `IoTSchool`
Executing (default): CREATE TABLE IF NOT EXISTS `Photons` (`id` INTEGER NOT NULL auto_increment , `sid` VARCHAR(255), `type` VARCHAR(255), `pid` VARCHAR(255) NOT NULL UNIQUE, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `SchoolId` INTEGER, PRIMARY KEY (`id`), FOREIGN KEY (`SchoolId`) REFERENCES `Schools` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `Photons` FROM `IoTSchool`
Executing (default): CREATE TABLE IF NOT EXISTS `Students` (`id` INTEGER NOT NULL auto_increment , `email` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `Students` FROM `IoTSchool`
Executing (default): CREATE TABLE IF NOT EXISTS `Users` (`id` INTEGER NOT NULL auto_increment , `username` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `Users` FROM `IoTSchool`
Executing (default): CREATE TABLE IF NOT EXISTS `Tasks` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `UserId` INTEGER NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`UserId`) REFERENCES `Users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `Tasks` FROM `IoTSchool`
Executing (default): CREATE TABLE IF NOT EXISTS `Teachers` (`teacherid` INTEGER auto_increment , `email` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`teacherid`)) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `Tasks` FROM `iotschoolmysql`
Unhandled rejection SequelizeConnectionError: Quit inactivity timeout
at Quit._callback (/Users/mitchell/Documents/deco3801/IoTSchool-Backend/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:104:30)
at Quit.Sequence.end (/Users/mitchell/Documents/deco3801/IoTSchool-Backend/node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)
at /Users/mitchell/Documents/deco3801/IoTSchool-Backend/node_modules/mysql/lib/protocol/Protocol.js:393:18
at Array.forEach (native)
at /Users/mitchell/Documents/deco3801/IoTSchool-Backend/node_modules/mysql/lib/protocol/Protocol.js:392:13
at process._tickCallback (node.js:355:11)
Unhandled rejection SequelizeConnectionError: Quit inactivity timeout
at Quit._callback (/Users/mitchell/Documents/deco3801/IoTSchool-Backend/node_modules/sequelize/lib/dialects/mysql/connection-manager.js:104:30)
at Quit.Sequence.end (/Users/mitchell/Documents/deco3801/IoTSchool-Backend/node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)
at /Users/mitchell/Documents/deco3801/IoTSchool-Backend/node_modules/mysql/lib/protocol/Protocol.js:393:18
at Array.forEach (native)
at /Users/mitchell/Documents/deco3801/IoTSchool-Backend/node_modules/mysql/lib/protocol/Protocol.js:392:13
at process._tickCallback (node.js:355:11)

Resources