I have 2 tables: user and photos (in a mysql db).
Here you can see the relation between the 2 tables
User Photos
----------------- -------------------------------
| id | user | | id_user | photo_url |
----------------- -------------------------------
|| /\
||______________________||
|________________________|
When I save a new user into the table "user", if the insert is done successfully, I have to take the value of the "id" field of the user just saved, and save it inside the "id_user" field of the table "photos", in order to make a relation between a user and its photos.
Making the first insert (table "user"), then getting, with a SELECT, the "id" of the last record and then again saving the user's photos it's not the right way to do it.
How should i do it?
To get the auto-incremented ID for the previous insert, you'll want to use mysql_insert_id().
use this toobtain user id:
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
30chars
Related
I have two tables (Leave, CompOff) I want to show these tables data to user(frontend) in form of Requests from employee. Employee can request for leave and compoff. Both the tables have createdOn, empid column. And I am not understanding how to fetch both table data and then return a list which contain both the tables data.
Leave tables -
empid | ceated_on
1 | 09-07-2022
2 | 05-07-2022
3 | 02-07-2022
CompOff tables -
empid | ceated_on
1 | 08-07-2022
2 | 06-07-2022
3 | 01-07-2022
In Springboot I have created three classes name - leave, compoff, request. And they have some create/update opertaion. Now in request class I want both (leave,compoff) data and send to user.
Use a union not a join.
Create a native query something like:
select 'leave' as type, empid, created_on, <other columns>
from leave
union all
select 'compoff', empid, created_on, <same other columns as above>
from compoff
i need a suggestion to store Mysql operations(insert/update)in a particular column of the table automatically like timestamp.
ex: table name: emptable
it contains 4 columns as empid, empname, password, dboperation
while inserting/updating i have to store the operation of the sql query automatically at the last column.
like below
|-----|-------|--------|-----------|
|empid|empname|password|dboperation|
|-----|-------|--------|-----------|
|1 |sai |asdf |insert |
|-----|-------|--------|-----------|
|1 |sairaj |asdf |update |
please suggest me how to do.
thanks in advance
In my application each user can have multiple authorization roles. Depending on his roles the user should be allowed to see certain excerpts of data. I want to provide this data from my relational database via a REST-API.
For example:
table "Role"
UserName | Role
---------------------------
Anne | ViewFreshFruits
Mike | ViewFreshFruits
Mike | ViewTinySoft
table "Company"
Name | Address | Role
--------------------------------------------
FreshFruits | 123 America | ViewFreshFruits
TinySoft | 543 Britain | ViewTinySoft
table "Contract"
ID | CompanyName | Dollar
---------------------------
147 | FreshFruits | 15549
148 | FreshFruits | 16321
149 | TinySoft | 2311
To implement the REST-Resource http://api:8080/Application/Contracts/getAll the data (without permission check) could simply be:
SELECT Contract.* FROM Contract
But Anne is only allowed to see 147 and 148. Mike can see 147, 148, 149. And Tomy must not get any results.
I started to implement the permission check like this:
SELECT Contract.* FROM Contract
INNER JOIN Company ON Contract.CompanyName = Company.Name
INNER JOIN Role ON Role.Role = Company.Role
WHERE User = #CurrentlyAuthenticatedUser
This kind of SQL gains complexity with the number of tables in my database. I'm looking for an easier approach: less complex and easier to maintain. Performance is not my primary concern.
How can I filter certain rows of data, depending on the user, as simple as possible?
I'm using a Microsoft SQL Server 2012, Java Tomcat 8 and Connection Pooling.
That seems the easiest way to create and maintain.
If you want to have a faster SQL query, that doesn't need joins, you could create a materialized view based on that query, but without the WHERE clause and with the User on the column selection.
SELECT User, Contract.* FROM Contract
INNER JOIN Company ON Contract.CompanyName = Company.Name
INNER JOIN Role ON Role.Role = Company.Role
That way you would have a virtual table that keeps that query saved and up to date for fast authentication data retrieval. To select you would only need to:
SELECT * FROM MaterializedView
WHERE User = #CurrentlyAuthenticatedUser
How about stored procedures where you pass the role. Or to simplify you select use a view to hide some of the details.
edit
Create a view on company and authorisation tables (or a stored procedure or CTE)
CREATE VIEW CompanySecurity AS SELECT Company.*, role.username FROM Company INNER JOIN Role ON Role.Role = Company.Role
If you want contract details join that view to CompanySecurity and filter on username
If you want to see Sales, join sales to CompanySecurity and filter on username
I am trying to understand that how object initialization works for returned object by Session Get method.Please validate my understanding. When it executes, it checks for object with given identifier in the first level cache and then the Second level cache (If it is configured), If not found then fires the select query to retrieve the data from database.
My question is, Does it include associations in select query which are configured for lazy loading or null value is set for such associations in returned object?
If this is case then session.get does not do the complete initialization of the returned object which is contradictory to what is written on most of hibernate tutorials available on web.
Hibernate Session provide different methods to fetch data from database. Two of them are – get() and load().
get() returns the object by fetching it from database or from hibernate cache.
when we use get() to retrieve data that doesn’t exists, it returns null, because it try to load the data as soon as it’s called.
We should use get() when we want to make sure data exists in the database.
For Example :
In a Stock application , Stock and StockTransactions should have a “one-to-many” relationship, when you want to save a stock transaction, it’s common to declared something like below.
Stock stock = (Stock)session.get(Stock.class, new Integer(2));
StockTransaction stockTransactions = new StockTransaction();
//set stockTransactions detail
stockTransactions.setStock(stock);
session.save(stockTransactions);
Output :
Hibernate:
select ... from mkyong.stock stock0_
where stock0_.STOCK_ID=?
Hibernate:
insert into mkyong.stock_transaction (...)
values (?, ?, ?, ?, ?, ?)
In session.get(), Hibernate will hit the database to retrieve the Stock object and put it as a reference to StockTransaction.
To answer the question:
Does it include associations in select query which are configured for lazy loading or null value is set for such associations in returned object?
1) The session.get() will NOT initiate lazy stuff. NEVER. In fact that is the central thought of the design. Otherwise - we would be able to load whole DB in one SHOT (in one JAVA call to session.get())
2) And also there WILL NOT be null instead. Each reference or collection will be represented by proxy. This is the way how we can avoid to load compelte DB in one shot (all stuff initialized with one method get). Because each proxy is in fact a promise - once we will touch it... it will load the real data.
And so on. So get is very safe way how to recieve as few data as was configured....
Simply
When get() method is called, it will directly hit the database, fetch the result and return. If no matching fields are found, it will gladly return null.
Depending on the annotations on references, Lazy or Eager, data will be returned. if Lazy, proxy will be returned instead of null, if Eager, fully initialized object will be returned.
Better to monitor the queries at the backend, for good understanding.
1) Customer entity class that map the T_CUSTOMER DB table:
#Entity
#Table(name= “T_CUSTOMER”)
public class Customer {
#Id
#Column (name=“cust_id”)
private Long id;
#OneToMany(fetch=FetchType.EAGER)
#JoinColumn (name=“cid”)
private Set<Address> addresses;
…
…
…
}
2) Address entity class that map the T_ADDRESS DB table:
#Entity
#Table(name= “T_ADDRESS”)
public class Address {
// Fields and Properties
}
Consider this Customers table :
----------------------------------------------------------------------------
| Cust_id | Cust_firstname | Cust_lastname | Cust_email | Cust_mobile |
----------------------------------------------------------------------------
| 101 | XXXX | YYYYY |xxx#xyz.com | 8282263131 |
----------------------------------------------------------------------------
The Above customers table is having one record with cust_id as 101.
Now Consider this Address Table :
----------------------------------------------------------------------------
| id | street | suburb | city | zipcode | cid |
----------------------------------------------------------------------------
| 1 | streetX | AreaY | cityZ | 54726 | 101 |
----------------------------------------------------------------------------
| 2 | streetXA | AreaYB | cityZS | 60660 | 101 |
----------------------------------------------------------------------------
Now When you invoke :
Customer cust = (Customer)session.get(Customer.class, 101);
Then Hibernate will fire a SQL Query Something like :
1). In case of EAGER LOADING :
SELECT * FROM T_CUSTOMER cust JOIN T_ADDRESS add ON cust.cust_id=add.cid
i.e, It will load all the data related to the T_CUSTOMERS table and it's associated tables, which is T_ADDRESS table in this case.
2). I case of LAZY LOADING :
SELECT * FROM T_CUSTOMER WHERE cust_id=101;
So, it only fetches the data corresponding to the T_CUSTOMER table and uses Proxy for the T_ADDRESS table as said above by #Radim Köhler. It will fetch the data from the T_ADDRESS TABLE only when you'll call :
cust.getAddresses();
From below table I want to extract the column values (C_Number) with the latest TimeStamp buy comparing with current system timestamp from db2 table? Please help.
Example: In Table "Computer" there are 3 columns i.e
C_Number | C_Data | TimeStamp
------------------------------------------------------------------------------
12-DFHK | Yes | 2013-08-14 07:33:05.29
13-DFCC | Yes | 2013-08-18 07:45:05.29
Form the above table how can i extract the Column "C_Number" values with latest Timestamp(in this above table latest timestamp is "2013-08-18 07:45:05.29" ) by comparing with current system time.
SELECT C_Number FROM Computer
WHERE TimeStamp = (SELECT MAX(TimeStamp) FROM Computer);
one more efficient way to achive your purpose is the following:
SELECT C_Number
FROM Computer
ORDER BY TimeStamp DESC
FETCH FIRST ROW ONLY ;