Hy .my problem is that i have a many to many relationship into a database , which is mapped with a table between the two tables.lets just say that i have the table Employees and Services with am many to many relationship, and the table between them is XXX. Now if i want to add an employee, and also to relate him to an service how do i do that if the primary key of Employees is on autoincrement?
I would have to insert the employee ..then to select it to find out his primary keyId and then to insert into the XXX table to relate to the service.Now my question is: Is there another way.? Sorry if this has been already answerew but i just didn`t know how to search for the a开发者_StackOverflow中文版nswer.Remider this i have to to in a java app. thxmy example:
create table employees(
id_employee primary key auto_increment
)
create table services(
id_service primary key auto_increment
)
and the midlle one
create table xxx(
id_employee primary key foreign key references employees(id_employee)
id_service primary key foreign key references services( id_service)
)
sorry about the haste..but i hope you get the ideea.Ps i am using MySql
You do not need to select, you can get the lastInsertedId from your database. Depending on what database you use it would be something different.
For mysql you can read about it here: http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
So
- insert
- get last inserted id not by selecting but just by asking the database (as it will return the last inserted id by your connection, not overal, this should be thread-safe).
- repeat :)
I just want to add my 5 cents to Nanne's reply. There are different ways how to retrieve last inserted id in Java if you are using Connector/J:
- using Statement.getGeneratedKeys(),
- using SELECT LAST_INSERT_ID(),
- using Updatable ResultSets.
精彩评论