Thursday, June 5, 2014

How I Explained REST to My Wife

How I Explained REST to My Wife

Ryan Tomayko

Sunday, December 12, 2004

Translations of the following dialog available in Japanese, French, Vietnamese, Italian, Spanish,Portuguese, and Chinese. Huge thanks to YAMAMOTO Yohei, Karl Dubost, jishin, Barbz, Tordek, Edgard Arakaki, keven lw, respectively. If you know of additional translations, please leave a comment with the location.

Wife: Who is Roy Fielding?

Ryan: Some guy. He's smart.

Wife: Oh? What did he do?

Ryan: He helped write the first web servers and then did a ton of research explaining why the web works the way it does. His name is on the specification for the protocol that is used to get pages from servers to your browser.

Wife: How does it work?

Ryan: The web?

Wife: Yeah.

Ryan: Hmm. Well, it's all pretty amazing really. And the funny thing is that it's all very undervalued. The protocol I was talking about, HTTP, it's capable of all sorts of neat stuff that people ignore for some reason.

Wife: You mean http like the beginning of what I type into the browser?

Ryan: Yeah. That first part tells the browser what protocol to use. That stuff you type in there is one of the most important breakthroughs in the history of computing.

Wife: Why?

Ryan: Because it is capable of describing the location of something anywhere in the worldfrom anywhere in the world. It's the foundation of the web. You can think of it like GPS coordinates for knowledge and information.

Wife: For web pages?

Ryan: For anything really. That guy, Roy Fielding, he talks a lot about what those things point to in that research I was talking about. The web is built on an architectural style called REST. REST provides a definition of a resource, which is what those things point to.

Wife: A web page is a resource?

Ryan: Kind of. A web page is a representation of a resource. Resources are just concepts. URLs--those things that you type into the browser...

Wife: I know what a URL is..

Ryan: Oh, right. Those tell the browser that there's a concept somewhere. A browser can then go ask for a specific representation of the concept. Specifically, the browser asks for the web page representation of the concept.

Wife: What other kinds of representations are there?

Ryan: Actually, representations is one of these things that doesn't get used a lot. In most cases, a resource has only a single representation. But we're hoping that representations will be used more in the future because there's a bunch of new formats popping up all over the place.

Wife: Like what?

Ryan: Hmm. Well, there's this concept that people are calling Web Services. It means a lot of different things to a lot of different people but the basic concept is that machines could use the web just like people do.

Wife: Is this another robot thing?

Ryan: No, not really. I don't mean that machines will be sitting down at the desk and browsing the web. But computers can use those same protocols to send messages back and forth to each other. We've been doing that for a long time but none of the techniques we use today work well when you need to be able to talk to all of the machines in the entire world.

Wife: Why not?

Ryan: Because they weren't designed to be used like that. When Fielding and his buddies started building the web, being able to talk to any machine anywhere in the world was a primary concern. Most of the techniques we use at work to get computers to talk to each other didn't have those requirements. You just needed to talk to a small group of machines.

Wife: And now you need to talk to all the machines?

Ryan: Yes - and more. We need to be able to talk to all machines about all the stuff that's on all the other machines. So we need some way of having one machine tell another machine about a resource that might be on yet another machine.

Wife: What?

Ryan: Let's say you're talking to your sister and she wants to borrow the sweeper or something. But you don't have it - your Mom has it. So you tell your sister to get it from your Mom instead. This happens all the time in real life and it happens all the time when machines start talking too.

Wife: So how do the machines tell each other where things are?

Ryan: The URL, of course. If everything that machines need to talk about has a corresponding URL, you've created the machine equivalent of a noun. That you and I and the rest of the world have agreed on talking about nouns in a certain way is pretty important, eh?

Wife: Yeah.

Ryan: Machines don't have a universal noun - that's why they suck. Every programming language, database, or other kind of system has a different way of talking about nouns. That's why the URL is so important. It let's all of these systems tell each other about each other's nouns.

Wife: But when I'm looking at a web page, I don't think of it like that.

Ryan: Nobody does. Except Fielding and handful of other people. That's why machines still suck.

Wife: What about verbs and pronouns and adjectives?

Ryan: Funny you asked because that's another big aspect of REST. Well, verbs are anyway.

Wife: I was just joking.

Ryan: It was a funny joke but it's actually not a joke at all. Verbs are important. There's a powerful concept in programming and CS theory called polymorphism. That's a geeky way of saying that different nouns can have the same verb applied to them.

Wife: I don't get it.

Ryan: Well.. Look at the coffee table. What are the nouns? Cup, tray, newspaper, remote. Now, what are some things you can do to all of these things?

Wife: I don't get it...

Ryan: You can get them, right? You can pick them up. You can knock them over. You can burn them. You can apply those same exact verbs to any of the objects sitting there.

Wife: Okay... so?

Ryan: Well, that's important. What if instead of me being able to say to you, "get the cup," and "get the newspaper," and "get the remote"; what if instead we needed to come up with different verbs for each of the nouns? I couldn't use the word "get" universally, but instead had to think up a new word for each verb/noun combination.

Wife: Wow! That's weird.

Ryan: Yes, it is. Our brains are somehow smart enough to know that the same verbs can be applied to many different nouns. Some verbs are more specific than others and apply only to a small set of nouns. For instance, I can't drive a cup and I can't drink a car. But some verbs are almost universal like GET, PUT, and DELETE.

Wife: You can't DELETE a cup.

Ryan: Well, okay, but you can throw it away. That was another joke, right?

Wife: Yeah.

Ryan: So anyway, HTTP--this protocol Fielding and his friends created--is all about applying verbs to nouns. For instance, when you go to a web page, the browser does an HTTP GET on the URL you type in and back comes a web page.

Web pages usually have images, right? Those are separate resources. The web page just specifies the URLs to the images and the browser goes and does more HTTP GETs on them until all the resources are obtained and the web page is displayed. But the important thing here is that very different kinds of nouns can be treated the same. Whether the noun is an image, text, video, an mp3, a slideshow, whatever. I can GET all of those things the same way given a URL.

Wife: Sounds like GET is a pretty important verb.

Ryan: It is. Especially when you're using a web browser because browsers pretty much justGET stuff. They don't do a lot of other types of interaction with resources. This is a problem because it has led many people to assume that HTTP is just for GETing. But HTTP is actually ageneral purpose protocol for applying verbs to nouns.

Wife: Cool. But I still don't see how this changes anything. What kinds of nouns and verbs do you want?

Ryan: Well the nouns are there but not in the right format.

Think about when you're browsing around amazon.com looking for things to buy me for Christmas. Imagine each of the products as being nouns. Now, if they were available in a representation that a machine could understand, you could do a lot of neat things.

Wife: Why can't a machine understand a normal web page?

Ryan: Because web pages are designed to be understood by people. A machine doesn't care about layout and styling. Machines basically just need the data. Ideally, every URL would have a human readable and a machine readable representation. When a machine GETs the resource, it will ask for the machine readable one. When a browser GETs a resource for a human, it will ask for the human readable one.

Wife: So people would have to make machine formats for all their pages?

Ryan: If it were valuable.

Look, we've been talking about this with a lot of abstraction. How about we take a real example. You're a teacher - at school I bet you have a big computer system, or three or four computer systems more likely, that let you manage students: what classes they're in, what grades they're getting, emergency contacts, information about the books you teach out of, etc. If the systems are web-based, then there's probably a URL for each of the nouns involved here: student, teacher, class, book, room, etc. Right now, getting the URL through the browser gives you a web page. If there were a machine readable representation for each URL, then it would be trivial to latch new tools onto the system because all of that information would be consumable in a standard way. It would also make it quite a bit easier for each of the systems to talk to each other. Or, you could build a state or country-wide system that was able to talk to each of the individual school systems to collect testing scores. The possibilities are endless.

Each of the systems would get information from each other using a simple HTTP GET. If one system needs to add something to another system, it would use an HTTP POST. If a system wants to update something in another system, it uses an HTTP PUT. The only thing left to figure out is what the data should look like.

Wife: So this is what you and all the computer people are working on now? Deciding what the data should look like?

Ryan: Sadly, no. Instead, the large majority are busy writing layers of complex specifications for doing this stuff in a different way that isn't nearly as useful or eloquent. Nouns aren't universal and verbs aren't polymorphic. We're throwing out decades of real field usage and proven technique and starting over with something that looks a lot like other systems that have failed in the past. We're using HTTP but only because it helps us talk to our network and security people less. We're trading simplicity for flashy tools and wizards.

Wife: Why?

Ryan: I have no idea.

Wife: Why don't you say something?

Ryan: Maybe I will.

Tuesday, May 20, 2014

Hibernate – One-To-Many Example


1. “One-to-many” example

This is a one-to-many relationship table design, a STOCK table has many occurrences STOCK_DAILY_RECORD table.
one to many table relationship
See MySQL table scripts
DROP TABLE IF EXISTS `stock`;
CREATE TABLE `stock` (
  `STOCK_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `STOCK_CODE` VARCHAR(10) NOT NULL,
  `STOCK_NAME` VARCHAR(20) NOT NULL,
  PRIMARY KEY (`STOCK_ID`) USING BTREE,
  UNIQUE KEY `UNI_STOCK_NAME` (`STOCK_NAME`),
  UNIQUE KEY `UNI_STOCK_ID` (`STOCK_CODE`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8;
 
 
DROP TABLE IF EXISTS `mkyongdb`.`stock_daily_record`;
CREATE TABLE  `mkyongdb`.`stock_daily_record` (
  `RECORD_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `PRICE_OPEN` FLOAT(6,2) DEFAULT NULL,
  `PRICE_CLOSE` FLOAT(6,2) DEFAULT NULL,
  `PRICE_CHANGE` FLOAT(6,2) DEFAULT NULL,
  `VOLUME` BIGINT(20) UNSIGNED DEFAULT NULL,
  `DATE` DATE NOT NULL,
  `STOCK_ID` INT(10) UNSIGNED NOT NULL,
  PRIMARY KEY (`RECORD_ID`) USING BTREE,
  UNIQUE KEY `UNI_STOCK_DAILY_DATE` (`DATE`),
  KEY `FK_STOCK_TRANSACTION_STOCK_ID` (`STOCK_ID`),
  CONSTRAINT `FK_STOCK_TRANSACTION_STOCK_ID` FOREIGN KEY (`STOCK_ID`) 
  REFERENCES `stock` (`STOCK_ID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8;
2. create model classes to map for tables

we already have a Stock.java class which was made under package package com.mkyong.common;
 first let's rename it to package com.mkyong.stock;
 so we have better packaging structure
 you have to do few modifications to support the one to many relationship
 
 or else you can make new Stock.java in new package
 
 
 ---------
 
 package com.mkyong.stock;

import static javax.persistence.GenerationType.IDENTITY;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = "stock", catalog = "mkyong", uniqueConstraints = {
@UniqueConstraint(columnNames = "STOCK_NAME"),
@UniqueConstraint(columnNames = "STOCK_CODE") })
public class Stock implements Serializable {

/**
* 
*/
private static final long serialVersionUID = 7029806795746254329L;
private Integer stockId;
private String stockCode;
private String stockName;

public Stock() {

}

public Stock(String stockCode, String stockName) {
this.stockCode = stockCode;
this.stockName = stockName;
}

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "STOCK_ID", unique = true, nullable = false)
public Integer getStockId() {
return stockId;
}

public void setStockId(Integer stockId) {
this.stockId = stockId;
}

@Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
public String getStockCode() {
return stockCode;
}

public void setStockCode(String stockCode) {
this.stockCode = stockCode;
}

@Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
public String getStockName() {
return stockName;
}

public void setStockName(String stockName) {
this.stockName = stockName;
}
}


-----------------------------------

for StockDailyRecord  create another java class






Errors
----------

1. AppOneToMany.java stockDailyRecords.setStock(stock);  was giving error, mapping to wrong Stock.java
previously on common package.
Reason : StockDailyRecord.java , I have imported import com.mkyong.common.Stock;
so the setter was mapped to com.mkyong.common.Stock;

2. Error in running application 
------------------------------

Hibernate one to many (Annotation)
May 20, 2014 4:11:34 PM org.hibernate.annotations.common.Version
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
May 20, 2014 4:11:34 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.4.Final}
May 20, 2014 4:11:34 PM org.hibernate.cfg.Environment
INFO: HHH000206: hibernate.properties not found
May 20, 2014 4:11:34 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 20, 2014 4:11:34 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
May 20, 2014 4:11:34 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
May 20, 2014 4:11:34 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
May 20, 2014 4:11:34 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Initial SessionFactory creation failed.org.hibernate.AnnotationException: Use of the same entity name twice: Stock
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.mkyong.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:20)
at com.mkyong.util.HibernateUtil.(HibernateUtil.java:8)
at com.mkyong.AppOneToMany.main(AppOneToMany.java:15)
Caused by: org.hibernate.AnnotationException: Use of the same entity name twice: Stock
at org.hibernate.cfg.annotations.EntityBinder.bindEntity(EntityBinder.java:402)
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:586)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3435)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3389)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1341)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1731)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1782)
at com.mkyong.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
... 2 more
Caused by: org.hibernate.DuplicateMappingException: duplicate import: Stock refers to both com.mkyong.stock.Stock and com.mkyong.common.Stock (try using auto-import="false")
at org.hibernate.cfg.Configuration$MappingsImpl.addImport(Configuration.java:2582)
at org.hibernate.cfg.annotations.EntityBinder.bindEntity(EntityBinder.java:395)
... 9 more

-------------------
Reason : I have included two entries in the "hibernate.cfg.xml"
  
 
 
  
  If you can see above , I have two entries for Stock.java   and
  
  Error itself gives asuggestion to 
  duplicate import: Stock refers to both com.mkyong.stock.Stock and com.mkyong.common.Stock (try using auto-import="false")
  
  solution 1 :First i try with removing one record, 
  execute
  
  ------------------ i still hvae an error--------------
  
  Hibernate one to many (Annotation)
May 20, 2014 4:18:52 PM org.hibernate.annotations.common.Version
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
May 20, 2014 4:18:52 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.4.Final}
May 20, 2014 4:18:52 PM org.hibernate.cfg.Environment
INFO: HHH000206: hibernate.properties not found
May 20, 2014 4:18:52 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 20, 2014 4:18:52 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
May 20, 2014 4:18:52 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
May 20, 2014 4:18:52 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
May 20, 2014 4:18:52 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Initial SessionFactory creation failed.org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: com.mkyong.stock.Stock.stockDailyRecords[com.mkyong.stock.StockDailyRecord]
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.mkyong.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:20)
at com.mkyong.util.HibernateUtil.(HibernateUtil.java:8)
at com.mkyong.AppOneToMany.main(AppOneToMany.java:15)
Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: com.mkyong.stock.Stock.stockDailyRecords[com.mkyong.stock.StockDailyRecord]
at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1204)
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:735)
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:670)
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:66)
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1591)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1366)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1731)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1782)
at com.mkyong.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
... 2 more

-----------------------
Reason to happen this error
http://stackoverflow.com/questions/4956855/hibernate-problem-use-of-onetomany-or-manytomany-targeting-an-unmapped-clas
Your annotations look fine. Here are the things to check:

make sure the annotation is javax.persistence.Entity, and not org.hibernate.annotations.Entity. The former makes the entity detectable. The latter is just an addition.

if you are manually listing your entities (in persistence.xml, in hibernate.cfg.xml, or when configuring your session factory), then make sure you have also listed the ScopeTopic entity

make sure you don't have multiple ScopeTopic classes in different packages, and you've imported the wrong one.


So I deleted all the classes Stock.java which was previously put inside to com.mkyong.common; package
I have been using it's references and I deleted all the references from App2.java and StockDetail.java classes

and it's runs fine
----------------

output will be 

---------------

Hibernate: insert into mkyong.stock (STOCK_CODE, STOCK_NAME) values (?, ?)
Hibernate: insert into mkyong.stock_daily_record (DATE, PRICE_CHANGE, PRICE_CLOSE, PRICE_OPEN, STOCK_ID, VOLUME) values (?, ?, ?, ?, ?, ?)
Done

-----------

if you need full detail output

-------------------------------------------------------------

Hibernate one to many (Annotation)
May 20, 2014 4:55:34 PM org.hibernate.annotations.common.Version
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
May 20, 2014 4:55:34 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.4.Final}
May 20, 2014 4:55:34 PM org.hibernate.cfg.Environment
INFO: HHH000206: hibernate.properties not found
May 20, 2014 4:55:34 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 20, 2014 4:55:34 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
May 20, 2014 4:55:34 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
May 20, 2014 4:55:34 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
May 20, 2014 4:55:34 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
May 20, 2014 4:55:35 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
May 20, 2014 4:55:35 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
May 20, 2014 4:55:35 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
May 20, 2014 4:55:35 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/mkyong]
May 20, 2014 4:55:35 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****}
May 20, 2014 4:55:35 PM org.hibernate.dialect.Dialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
May 20, 2014 4:55:35 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
May 20, 2014 4:55:35 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
May 20, 2014 4:55:35 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: insert into mkyong.stock (STOCK_CODE, STOCK_NAME) values (?, ?)
Hibernate: insert into mkyong.stock_daily_record (DATE, PRICE_CHANGE, PRICE_CLOSE, PRICE_OPEN, STOCK_ID, VOLUME) values (?, ?, ?, ?, ?, ?)
Done








------------------------------------------------











Ruannable vs Callable



"The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception."

RunnableCallable>
Introduced in Java 1.0Introduced in Java 1.5 as part of java.util.concurrent library
Runnable cannot be parametrized Callable is a parametrized type whose type parameter indicates the return type of its run method
Classes implementing Runnable needs to implement run() methodClasses implementing Callable needs to implement call() method
Runnable.run() returns no ValueCallable.call() returns a value of Type T
Can not throw Checked ExceptionsCan throw Checked Exceptions
public class RunnableTest implements Runnable {
              @Override
              public void run() {
                         //any processing
              }
}
import java.util.concurrent.Callable;


public class CallableTest implements Callable { 
          @Override 
           public String call() throws Exception { 
                      // any processing
                    return new String("I am Callable and can return value and throw checked exception"); 
              } 
}

Tuesday, May 13, 2014

hibernate.dialect

Dialect means "the variant of a language". 
Hibernate, as we know, is database agnostic. It can work with different databases. 
However, databases have proprietary extensions/native SQL variations, and set/sub-set of SQL standard implementations.
Therefore at some point hibernate has to use database specific SQL.
So Hibernate uses "dialect" configuration to know which database you are using so that it can switch to the database specific SQL generator code wherever/whenever necessary.


In simple

hibernate.dialect property helps Hibernate to generate the appropriate SQL statements for the chosen database.

List of Hibernate SQL Dialects
http://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/dialect/package-summary.html


hibernate.cfg.xml

what is this. why we need this.
Hibernate needs to know "in Advance" the mapping details that defines how the java classes are related to database tables.
Hibernate needs to set configuration settings related to database and other related parameters.

The information will be given through a standard java property file called "hibernate.properties"  or the "hibernate.cfg.xml".

The file will reside inside the root directory of your application classpath.


basically this file may look like this

---------------------

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">


  com.mysql.jdbc.Driver
  jdbc:mysql://localhost:3306/mkyong
  root
  root123
  org.hibernate.dialect.MySQLDialect
 
  true
 
 




let's see what these all about

S.N.Properties and Description
1hibernate.dialect 
This property makes Hibernate generate the appropriate SQL for the chosen database.
2hibernate.connection.driver_class 
The JDBC driver class.
3hibernate.connection.url 
The JDBC URL to the database instance.
4hibernate.connection.username 
The database username.
5hibernate.connection.password 
The database password.
6hibernate.connection.pool_size 
Limits the number of connections waiting in the Hibernate database connection pool.
7hibernate.connection.autocommit 
Allows autocommit mode to be used for the JDBC connection.

If you are using a database along with an application server and JNDI then you would have to configure the following properties:
S.N.Properties and Description
1hibernate.connection.datasource 
The JNDI name defined in the application server context you are using for the application.
2hibernate.jndi.class 
The InitialContext class for JNDI.
3hibernate.jndi. 
Passes any JNDI property you like to the JNDI InitialContext.
4hibernate.jndi.url 
Provides the URL for JNDI.
5hibernate.connection.username 
The database username.
6hibernate.connection.password 
The database password.

Monday, May 12, 2014

Create Hibernate Project with annotation hibernate + mysql

Create a maven project and build it to support the hibernate

1. create maven project

execute below command
you need to have maven in your system

mvn archetype:generate -DgroupId=com.mkyong -DartifactId=HibernateExample -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

eg:

C:\example\Tutorial\Hibernate>mvn archetype:generate -DgroupId=com.mkyong -DartifactId=HibernateExample -DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom <<<
[INFO]
[INFO] --- maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Batch mode
Downloading: http://repo1.maven.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.jar
Downloaded: http://repo1.maven.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.jar (5 KB at 2.0 K
B/sec)
Downloading: http://repo1.maven.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.pom
Downloaded: http://repo1.maven.org/maven2/org/apache/maven/archetypes/maven-archetype-quickstart/1.0/maven-archetype-quickstart-1.0.pom (703 B at 1.3
KB/sec)
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: com.mkyong
[INFO] Parameter: packageName, Value: com.mkyong
[INFO] Parameter: package, Value: com.mkyong
[INFO] Parameter: artifactId, Value: HibernateExample
[INFO] Parameter: basedir, Value: C:\example\Tutorial\Hibernate
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: C:\example\Tutorial\Hibernate\HibernateExample
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 19.246s
[INFO] Finished at: Fri May 09 11:22:11 IST 2014
[INFO] Final Memory: 6M/16M
[INFO] ------------------------------------------------------------------------
C:\example\Tutorial\Hibernate>


This will create simple maven project with 
/HibernateExample/src/main/java/com/mkyong/App.java 
/HibernateExample/src/test/java/com/mkyong/AppTest.java



---------  pom will have---
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  4.0.0
  com.mkyong
  HibernateExample
  jar
  1.0-SNAPSHOT
  HibernateExample
  http://maven.apache.org
  
 
  
   
      junit
      junit
      3.8.1
      test
   
    
 
  


----------------
you can refer below also for with oracle
http://www.mkyong.com/hibernate/maven-3-hibernate-3-6-oracle-11g-example-xml-mapping/


we need to create table

let's create a table name with "Stock" . below will be sql

DROP TABLE IF EXISTS `stock`;
CREATE TABLE `stock` (
  `STOCK_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `STOCK_CODE` VARCHAR(10) NOT NULL,
  `STOCK_NAME` VARCHAR(20) NOT NULL,
  PRIMARY KEY (`STOCK_ID`) USING BTREE,
  UNIQUE KEY `UNI_STOCK_NAME` (`STOCK_NAME`),
  UNIQUE KEY `UNI_STOCK_ID` (`STOCK_CODE`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;



2. then we need to create a java class to map table, hibernate mapping classs

package com.mkyong.common;

import static javax.persistence.GenerationType.IDENTITY;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = "stock", catalog = "mkyong", uniqueConstraints = {
@UniqueConstraint(columnNames = "STOCK_NAME"),
@UniqueConstraint(columnNames = "STOCK_CODE") })
public class Stock implements Serializable {

/**
* 
*/
private static final long serialVersionUID = 7029806795746254329L;
private Integer stockId;
private String stockCode;
private String stockName;

public Stock() {

}

public Stock(String stockCode, String stockName) {
this.stockCode = stockCode;
this.stockName = stockName;
}

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "STOCK_ID", unique = true, nullable = false)
public Integer getStockId() {
return stockId;
}

public void setStockId(Integer stockId) {
this.stockId = stockId;
}

@Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
public String getStockCode() {
return stockCode;
}

public void setStockCode(String stockCode) {
this.stockCode = stockCode;
}

@Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
public String getStockName() {
return stockName;
}

public void setStockName(String stockName) {
this.stockName = stockName;
}
}



------------------------------------------

3. We need a Hibernate utill class to create hibernate session factory 

-------------------

package com.mkyong.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();
 
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml - for XML mapping
// return new Configuration().configure().buildSessionFactory();
// for annotations
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
 
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
 
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}


-----------------------


to make the hibernate configuration we need hibernate configuration file.

/HibernateExample/src/main/resources/hibernate.cfg.xml

-----------------------------------


"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 
  com.mysql.jdbc.Driver
  jdbc:mysql://localhost:3306/mkyong
  root
  root123
  org.hibernate.dialect.MySQLDialect
 
  true
 
 


-------------------------------


4. we need to add dependency to the pom file. without dependency code even compile.]
this is first most steps.
you can start project with adding dependency
/HibernateExample/pom.xml

--------------
org.hibernate
hibernate-core
4.1.4.Final


org.hibernate.common
hibernate-commons-annotations
4.0.1.Final


mysql
mysql-connector-java
5.1.9



javassist
javassist
3.12.1.GA

----------------------------------------------------

pom.xml willl be finally looks like this
----------------------------------------------------------


xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
com.mkyong
HibernateExample
jar
1.0-SNAPSHOT
HibernateExample
http://maven.apache.org


junit
junit
3.8.1
test

org.hibernate
hibernate-core
4.1.4.Final


org.hibernate.common
hibernate-commons-annotations
4.0.1.Final


mysql
mysql-connector-java
5.1.9



javassist
javassist
3.12.1.GA



org.codehaus.mojo
exec-maven-plugin
1.2.1
java
com.mkyong.App2
foo
bar



------------------------------------------------------------------


org.codehaus.mojo
exec-maven-plugin
1.2.1
java
com.mkyong.App2
foo
bar



this is to run main method
-------------------------------------------------------

5. Finally we need to test class to test our hibernate project. We create App2.java class

---------------------

package com.mkyong;

import org.hibernate.Session;

import com.mkyong.common.Stock;
import com.mkyong.util.HibernateUtil;

public class App2 {
public static void main(String[] args) {
System.out.println("Maven + Hibernate + MySQL");
Session session = HibernateUtil.getSessionFactory().openSession();

session.beginTransaction();
Stock stock = new Stock();

stock.setStockCode("4716");
stock.setStockName("SN4716");

session.save(stock);
session.getTransaction().commit();
}
}


-----------------------