I am working on a stand-alone Java project (not Java EE), I am currently learning JDBC, I am creating a database where it contains Employee information, such as Personal information, Contact Information, Employee Information and Tax information, all of these are classes with references with each other and they have setters and getters, I am wondering how would I insert their data value in the database/tables I created in the database? in short I have Employee an employee object with like this
Employee(PersonalInformation information,ContactInformation cInformation)
Something like that, how would I add their data in the tables I made in the database?
how would I add their data in the tables I made in the database?
By using JDBC to send INSERT statements to the database, one for each object in your object graph (assuming you have one table per class).
And yes, that's a lot of boring, repetitive code to write, which is likely to contain errors and quite a burden to maintain.
Which is why people have written Object-Relational mappers like Hibernate, and there's a Java standard for that called JPA. Which is part of Java EE, but that doesn't mean you have to run a Java EE server to use it.
Update: OK, so you cannot use an ORM, probably because you're supposed to understand how JDBC works first, which makes sense because ORMs are based on JDBC and sometimes you have to go down to that level when there is a problem.
When using JDBC directly, you typically create a DAO (data ccess object) layer that is responsible for writing and reading objects to/from the database. For dealing with a nested object, one DAO can call the other.
And no, the DAOs are not called in the setters and getters. There called by the part of your application that reacts to user input. E.g. when the user opens the application and the start screen shows a list of employees, you'd call an EmployeeDAO.findAll() method, and when the user makes changes to an employee and clicks on "save", you'd call the EmployeeDAO.save() method.
I recommend you to look at Spring's JdbcTemplate (http://www.java2s.com/Code/Java/Spring/ControlParameterTypeInJdbcTemplateQuery.htm)
Its looks like this:
SingleConnectionDataSource ds = new SingleConnectionDataSource();
ds.setDriverClassName("org.hsqldb.jdbcDriver");
ds.setUrl("jdbc:hsqldb:data/tutorial");
ds.setUsername("sa");
ds.setPassword("");
JdbcTemplate jt = new JdbcTemplate(ds);
jt.execute("insert into employee (id, name) values (?, ?)", 1, "Tom");
Use one jdbcTemplate per DAO class instance.
This may help you
Pass all the required values to the respective objects.
get all their values and frame a query using those values like
Employee em = new Employee(perinfo, continfo);
String emp_per_info = em.getSomeInfo(); // it this returns a string
...
//so on
query="insert into table_name values(variables go here);"
let me know if it didn't work
What you are trying to do is called "Object to Relational Mapping". You have the java Objects which make up your object domain and there is the DB Table which make up the relational model. You have relate them. Save the data and query to get them back.
You have two approaches to write a kind of your own limited framework or use an existing framework. Existing frameworks include :
Hibernate
iBatis
and so on.
To do one on your own, simplest way to do would be writing simple result set to object mappers and creating insert strings.
I would suggest you study some ORM docs to know more.
Regards
Related
I am currently studying Java Serialization. However, I am still confused about its practicality. Generally speaking, when are we supposed to use serialisation in comparison to storing data directly in various database columns?
I think you are confusing Serialization with reading and writing an Object to a database.
As explained in this SO answer Do Hibernate table classes need to be Serializable? JPA objects (which hibernate is) should implement Serializable so that detached entities can be sent to other layers of your application possibly via RMI.
This has nothing to do with how Hibernate reads and writes data to a database. As long as you don't use detached objects you can get away with not having your entities implement Serializable and hibernate will still work just fine.
Hibernate reads and writes to a database via JDBC just like you would if you were writing the SQL queries yourself. If you want to learn more about how hibernate converts your object fields to JDBC methods you can start by looking at Hibernate UserType. Hibernate comes by default with a lot of built in User Types that can convert ResultSet columns of types String, Date, int etc to and from the database. If you need to write your own UserTypes which happens on occasion, you just have to write your own UserType implementation which is pretty simple.
Hibernate-enhanced classes can actually be Serializable. However, you should think about all the outcomes before you use it that way. You may encounter those problems:
if your class has collections of related DB entities, extra queries will be made to load those
if you have bidirectional relation in classes, you can experience a stack overflow
to prevent this behavior, you will need to specify the serialization somehow (e.g. using some #Json* annotations if you serialize to JSON)
if your class only contains IDs, you're fine (but you are losing a lot of Hibernate's goodness)
To understand those problems, you need to know how Hibernate actually works.
The enhancement allows the entity to be partially loaded. E.g., you want to get all books for given user. You get a collection of books, but what you really have is a collection of hibernate-enhanced classes, that only wrap IDs at the moment. Provided that you use the default lazy loading.
Unless you really need something else than IDs, the data will never be loaded. Upon a getter call, background queries are made to obtain the extra information, if needed.
Now, imagine a user has a collection of all his books, as a field. When lazily loaded from DB, there may be nothing at all. However, if you want to serialize it, all getters are called and you get all the books, and transitively, every book author, should the books have a relation to its authors ...
If the relation is bidirectional in the classes, you can even create a cycle that will cause a stack overflow error, where you look who's the book's owner and then you fetch books for him again.
I seem to keep tripping over this problem. And I can't seem to get a straight answer on the way to approach it.
I have an MVC web app using Java, Tomcat, JSP, MySQL, etc. I'm not using a framework. I have Model Entities representing each table in the database. I'm using DAOs to access the database.
Say you have a Person, a Job, and an Application.
In the View, you need to relate those together to produce a row for a listing.
So far, I've been doing JOINs in the DAO and returning a long SQL Result from the ResultSet using ResultSupport. Then I loop through it in the JSP using a JSTL forEach tag.
I understand this is not the best way to do it.
But then, what is it I need to create in the DAO to pass back each row of data? Do I define a new object with all the field names I need in the view? Is this a DTO? Or do I stuff the original objects in a HashMap and pass back that?
When I ask the database, I assume that doing a join is going to be more efficient than doing a bunch of small queries to return the individual objects.
There must be an accepted pattern for doing this? I would prefer to just follow an accepted solution.
Can someone please point me in the right direction?
Thanks
If you only have one single view, then creating a plain old java object (POJO) works fine. I would create an POJO which contains all the fields you need for a view. Then create a collection (E.G. ArrayList). The collection of POJO's is your Data Transfer Object (DTO).
The database connections are costly. So you want to open the database, get the data and store it your POJO collection. You then either close database connection or return to a pool (if you are using database connection pool). The point is, don't try to create an html display while holding on to a live database connection. Get the data, close the database connection (or return to a pool), then perform your display logic (I.E. the View).
Yes, you want to select all the information at once (do a database join). Same idea, use the database connection and then close it as quickly as possible. You want to avoid multiple open/close, open/close, etc.
Hopefully that helps. You might want to narrow down your question to something more specific. It's really difficult for folks to answer broad architectural questions . Good Luck.
Can someone please explain the best way to solve this problem.
Suppose I have three classes
1.Person
2.Venue
3.Vehicle
I have a DAO method that needs to return some or all of these attributes from each of the classes after doing a query.
How do I accomplish this ? It seems very wrong to make a class PersonVenueVehicle and return that as an object to get the instance field, values.
I was taught that the database entities must be reflected by classes, if this is case how is it implemented in such a situation
Try the Spring-ish solution. Besides your three classes, you can have 3 DAO classes, one for each. But you have a task to perform; I don't know what it is; I'm just going to guess.
Suppose you are running a taxi service; Persons schedule through your company taxis to pick them up at a Venue, and you send them a Vehicle. Call this combination a Trip, and now you want a class that manages Trips in the database. Create a class called TripService. This should use your PersonDao, your VenueDao, and your VehicleDao to create if necessary person and venue records in the database, and should do the calculations needed to choose which Vehicle to use. When it does, it should use a new TripDao to persist a new Trip object. But, as the organizer, it should create and vend the database connection to all the DAOs, and should do the commit or rollback itself.
If you're using Hibernate or JPA, your classes could be modified. But the principle is the same. Even if I have your motivation wrong, you can write a service that coordinates the three DAOs and vends the connection. It can, if it has to, use the connection itself to do a SELECT on the three tables JOINed together.
You lose much of the benefits of a database if the only statements you write are simple SELECTs and UPDATEs and INSERTs
I am developing a program in Java that I will use for registering data. I store the data in a MySQL database. We have not been making "big" programs in my class that uses databases for storage so what we have done is to make an adapter(We usually name it DBAdapter or something) that creates the connection and returns it. Then we have made a database handler class where all the statements are being executed. Then last the controller + view class have a reference to this handler and call whatever methods available.
However, my question is: When dealing with multiple tables and maybe different model data wouldn't it be good to separate the code in the handler into smaller chunks? Such as private classes or other public classes that a "main" handler could have references too? Example: If you make a system for a company that ship goods you probably would have a database that stores data about the goods. Then you would have a handler that has many select-statments for various stuff. You would also have many employees and then you probably want to separate the select-statements for the goods from the select-statements for the employees.
I also wonder if handler/adapter etc. is the correct terminology?
(This is not homework btw. I am making a program that will be a used for registering data for my iPhone app)
Thank you for your time.
You may want to look into Object-relational mapping libraries for Java, such as OpenJPA or Hibernate. If you'd rather stick to SQL - or like the fine-grained control - you may find Ibatis interesting.
In any case, I wouldn't manage the connections to the DB myself but rely on a connection pool, usually accessed through the DataSource interface.
While ORM may well be where you head, I'd start with
a connection pool
implementing a DAO pattern strategy. If you are using Spring, look at JDBCTemplate - it will be pretty easy to convert this to HibernateTemplate, etc.
I want to copy all data of a specific table from database1 to database2. In my system i have access via hibernate to the domain object from database1, i don't have to transform the data-structure. i have only a native jdbc connection to database2.
whats the best solution to make this groovy script very generally to support all kinds of domain objects i have? so this script only gets my domain object and the connection string to database and inserts all the data?
I faced a similar issue where I needed the ability to export every hibernate entity to an SQL script, in other words if you had a Person object with two properties (username, password) you should be able to generate the SQL insert statement of that Object.
Person.username = x
Person.password = y
then the process would extract from that object the equivalent SQL insert and create something like:
insert into person (username, password) values ('x', 'y');
However my solution was based on the fact that mappings are done using hibernate annotations and not XML configuration, if this is your case you could achieve the same with 1 or 2 working days, just read the annotations. noting that you will have to do an extra step which is executing the resulted SQL inserts on the other DB.
FYI: this method toSQL() was added in a superclass (AbstractHibernateEntity) that every hibernate entity extended, so calling it was the easiest thing to do.
This was the complicated solution and most general one, however if you only need to copy one table from DB to another I would suggest to simple go with a simple JDBC call and avoid complicating your life ;-)
Regards.
Maybe the easiest would be to stick on the technology level that is common to both databases.
If they exist, you could use database-specific commands, that would be really fast.
If not, you could use simple jdbc on both. You could that in a generic way :-)