tag:blogger.com,1999:blog-56552581761178007352024-03-14T14:55:53.173+05:30Java by examplesVicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.comBlogger275125tag:blogger.com,1999:blog-5655258176117800735.post-74007933134767932462021-09-25T13:05:00.003+05:302021-09-25T13:05:54.222+05:30Builder Design Pattern in Java<div dir="ltr" style="text-align: left;" trbidi="on">
The builder pattern, as the name suggest, we can use this pattern to
build/construct complex objects. We should use this pattern when we want to
construct same type of
<a class="externalLink" href="https://www.javaquery.com/2019/12/how-to-create-immutable-class-in-java.html?utm_source=javaquery" target="_blank">immutable objects</a>
with different sets of attributes.
</div>
<div dir="ltr" style="text-align: left;" trbidi="on"><br /></div>
<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-size: x-large;"><b>Goal of Builder Design Pattern</b></span>
(<a class="externalLink" href="https://en.wikipedia.org/wiki/Builder_pattern?utm_source=javaquery" target="_blank">https://en.wikipedia.org/wiki/Builder_pattern</a>)<br />
</div>
<div class="blockquote" dir="ltr" style="text-align: left;" trbidi="on">
The goal of Builder design pattern is to separate the construction of a
complex object from its representation so the same construction process can
create different representations.<br />
</div>
<div dir="ltr" style="text-align: left;" trbidi="on"> </div>
<div dir="ltr" style="text-align: left;" trbidi="on">
Now lets understand the builder design pattern with real world example. We all
have <b>Contact</b> details in our mobile. Now lets construct
<b>Contact</b> object with different sets of attributes.<br />
</div>
<div dir="ltr" style="text-align: left;" trbidi="on">
For any <b>Contact</b> in our mobile, name is required data however email,
mobile number, address, birthday are optional attributes. Now if we want to
create immutable <b>Contact</b> object then constructor would look like as
follow.</div><br />
<span style="font-size: large;"><b>Source code (Contact.java)</b></span>
<pre class="prettyprint">/**
* @author javaQuery
* @date 2021-09-07
* @Github: https://github.com/javaquery/Examples
*/
public Contact{
private String name;
private String email; // can be list of emails
private String mobile; // can be list fo mobiles
private String address;
private Date birthday;
public Contact(String name, String email, String mobile, String address, Date birthday){
this.name = name;
this.email = email;
this.mobile = mobile;
this.address = address;
this.birthday = birthday;
}
}
</pre>
<div dir="ltr" style="text-align: left;" trbidi="on">
In above example if you notice that even though email, mobile, etc... are
optional to construct <b>Contact</b> object we have to pass
<b class="inlineCode">null</b> value for optional attributes. What other
option we can think of is to create different constructor as per the
requirements.
</div>
<pre class="prettyprint"> public Contact(String name, String email){...}
public Contact(String name, String mobile){...}
public Contact(String name, String email, String mobile){...}
public Contact(String name, String email, String mobile, String address){...}
...
...
</pre>
<div dir="ltr" style="text-align: left;" trbidi="on">
Now what if we introduce another attribute <b>anniversary</b>?
<b>Contact</b> object constructor would become more complex and hard to
handle. <br />
</div>
<div dir="ltr" style="text-align: left;" trbidi="on"> </div>
<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-size: x-large;"><b>Builder pattern in action</b></span>
</div>
<div dir="ltr" style="text-align: left;" trbidi="on">
Now lets use builder pattern to construct <b>Contact</b> object. We will take help of
inner <b>Builder</b> class to construct the <b>Contact</b> object.</div><div dir="ltr" style="text-align: left;" trbidi="on"><br />
<span style="font-size: large;"><b>Source code (Contact.java)</b></span>
<pre class="prettyprint">import java.util.Date;
/**
* @author javaQuery
* @date 2021-09-21
* @Github: https://github.com/javaquery/Examples
*/
public class Contact {
private final String name;
private final String email; // can be list of emails
private final String mobile; // can be list fo mobiles
private final String address;
private final Date birthday;
public Contact(Builder builder) {
this.name = builder.name;
this.email = builder.email;
this.mobile = builder.mobile;
this.address = builder.address;
this.birthday = builder.birthday;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getMobile() {
return mobile;
}
public String getAddress() {
return address;
}
public Date getBirthday() {
return birthday;
}
@Override
public String toString() {
return "Contact{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
", mobile='" + mobile + '\'' +
", address='" + address + '\'' +
", birthday=" + birthday +
'}';
}
public static class Builder{
private final String name;
private String email; // can be list of emails
private String mobile; // can be list fo mobiles
private String address;
private Date birthday;
public Builder(String name) {
this.name = name;
}
public Builder email(String email){
this.email = email;
return this;
}
public Builder mobile(String mobile){
this.mobile = mobile;
return this;
}
public Builder address(String address){
this.address = address;
return this;
}
public Builder birthday(Date birthday){
this.birthday = birthday;
return this;
}
public Contact build(){
return new Contact(this);
}
}
}
</pre>
<span style="font-size: large;"><b>Source code (BuilderMain.java)</b></span><br />Using Builder class to construct the Contact object.
<pre class="prettyprint">import java.util.Date;
public class BuilderMain {
public static void main(String[] args) {
Contact contactVicky = new Contact.Builder("Vicky")
.email("vicky.thakor@javaquery.com")
.build();
System.out.println(contactVicky);
Contact contactKrupa = new Contact.Builder("Krupa")
.birthday(new Date())
.build();
System.out.println(contactKrupa);
}
}
</pre>
</div>
<div dir="ltr" style="text-align: left;" trbidi="on"><br /><span style="font-size: x-large;"><b>Builder pattern in JDK</b></span><br /><b class="inlineCode">java.lang.StringBuilder</b> and <b class="inlineCode">java.lang.StringBuffer</b> are widely known class which uses Builder Design Pattern. Using method <b class="inlineCode">append(....)</b> you can construct the final object as per your requirements.</div><div dir="ltr" style="text-align: left;" trbidi="on"> </div><div dir="ltr" style="text-align: left;" trbidi="on"> </div><div dir="ltr" style="text-align: left;" trbidi="on"> </div><div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0San Francisco Bay Area, CA, USA37.8271784 -122.29130789.5169445638211556 -157.4475578 66.137412236178847 -87.1350578tag:blogger.com,1999:blog-5655258176117800735.post-52513119268036391192021-09-24T09:56:00.002+05:302021-09-24T09:56:40.033+05:30org.redisson.client.RedisException: Unexpected exception while processing command<div>
<pre class="prettyprint">
org.redisson.client.RedisException: org.redisson.client.RedisException: Unexpected exception while processing command
at jdk.internal.reflect.GeneratedConstructorAccessor358.newInstance(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
at java.base/java.util.concurrent.ForkJoinTask.getThrowableException(ForkJoinTask.java:600)
at java.base/java.util.concurrent.ForkJoinTask.reportException(ForkJoinTask.java:678)
at java.base/java.util.concurrent.ForkJoinTask.invoke(ForkJoinTask.java:737)
at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateParallel(ForEachOps.java:159)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateParallel(ForEachOps.java:173)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:233)
at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:661)
at jdk.internal.reflect.GeneratedMethodAccessor1318.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.servlet.resource.ResourceUrlEncodingFilter.doFilter(ResourceUrlEncodingFilter.java:65)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:109)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:764)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: org.redisson.client.RedisException: Unexpected exception while processing command
at org.redisson.command.CommandAsyncService.convertException(CommandAsyncService.java:352)
at org.redisson.command.CommandAsyncService.get(CommandAsyncService.java:149)
at org.redisson.RedissonObject.get(RedissonObject.java:81)
at org.redisson.RedissonMap.get(RedissonMap.java:618)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at java.base/java.util.stream.ForEachOps$ForEachTask.compute(ForEachOps.java:290)
at java.base/java.util.concurrent.CountedCompleter.exec(CountedCompleter.java:746)
at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183)
Caused by: java.io.IOException: java.lang.ClassNotFoundException: com.xxx.xxx.xxx
at org.redisson.codec.MarshallingCodec$3.decode(MarshallingCodec.java:153)
at org.redisson.client.handler.CommandDecoder.decode(CommandDecoder.java:359)
at org.redisson.client.handler.CommandDecoder.decodeCommand(CommandDecoder.java:178)
at org.redisson.client.handler.CommandDecoder.decode(CommandDecoder.java:117)
at org.redisson.client.handler.CommandDecoder.decode(CommandDecoder.java:102)
at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:508)
at io.netty.handler.codec.ReplayingDecoder.callDecode(ReplayingDecoder.java:366)
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1533)
at io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1282)
at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1329)
at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:508)
at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:447)
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:719)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:655)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:581)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493)
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: java.lang.ClassNotFoundException: com.xxx.xxx.xxx
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:398)
at org.jboss.marshalling.AbstractClassResolver.loadClass(AbstractClassResolver.java:129)
at org.jboss.marshalling.AbstractClassResolver.resolveClass(AbstractClassResolver.java:110)
at org.jboss.marshalling.river.RiverUnmarshaller.doReadClassDescriptor(RiverUnmarshaller.java:1033)
at org.jboss.marshalling.river.RiverUnmarshaller.doReadNewObject(RiverUnmarshaller.java:1366)
at org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:283)
at org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:216)
at org.jboss.marshalling.AbstractObjectInput.readObject(AbstractObjectInput.java:41)
at org.redisson.codec.MarshallingCodec$3.decode(MarshallingCodec.java:151)
... 32 common frames omitted
</pre>
To fix the exception you need to set codec for your redisson. By using
<b class="inlineCode">org.redisson.codec.SerializationCodec</b> I was able to resolve the issue.
</div>
<div>
<pre class="prettyprint">
Config config = new Config();
config.setCodec(new org.redisson.codec.SerializationCodec());
</pre>
</div>
<div> </div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0San Francisco Bay Area, CA, USA37.8271784 -122.29130789.5169445638211556 -157.4475578 66.137412236178847 -87.1350578tag:blogger.com,1999:blog-5655258176117800735.post-35146743818263387112021-09-07T18:05:00.002+05:302021-09-07T18:05:29.509+05:30Exception Handling with Method Overriding in Java<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-yCQqcVC6Egg/YTdQC0sPM8I/AAAAAAAAH1U/8TD9jgoKStU4Bs3moNqtEc0-n_m7UIcugCPcBGAYYCw/s700/Java%2B%252B%2BException.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="300" data-original-width="700" src="https://1.bp.blogspot.com/-yCQqcVC6Egg/YTdQC0sPM8I/AAAAAAAAH1U/8TD9jgoKStU4Bs3moNqtEc0-n_m7UIcugCPcBGAYYCw/s16000/Java%2B%252B%2BException.png" /></a>
</div>
<br />
<div>
In our day to day programming we use method overriding widely. Have you ever
considered how exception handling rule works in method overriding? Lets see
how it works in Java with example. </div><div> </div>
<div>
<b><span style="font-size: medium;">RULE 1. Super class method does not declare any exception in its method
signature.</span></b>
</div>
<div>
If super class method does not declared any exception in its method signature
then sub-class's over ridden method can not declare any checked exception
however it can declare any unchecked/RuntimeException. Following example demonstrate the first rule of exception. </div><div> </div>
<div>
<b><span style="font-size: large;">Source code (SuperClassExceptionRule1.java)</span></b>
</div>
<pre class="prettyprint">/**
* Example of SuperClassExceptionRule1 in java.
* @author javaQuery
* @date 2021-09-07
* @Github: https://github.com/javaquery/Examples
*/
public class SuperClassExceptionRule1 {
public void methodWithoutException(){
System.out.println("methodWithoutException");
}
public static void main(String[] args) {
System.out.printf("SuperClassExceptionRule1");
}
public class ChildClassExceptionRule1 extends SuperClassExceptionRule1{
// Compile time error when tried to throw checked exception
// @Override
// public void methodWithoutException() throws Exception{
// super.methodWithoutException();
// }
// Allowed to throw unchecked exception (i.e Any RuntimeException)
@Override
public void methodWithoutException() throws RuntimeException{
super.methodWithoutException();
}
}
}
</pre>
<span style="font-size: medium;"><b>RULE 2. Super class method declared exception in its method signature.</b></span>
<div>
If super class method declared any exception in its method signature then
sub-class's over ridden method can declare same exception, any child/sub-class
exception or no exception however you can not declare parent exception. Following example demonstrate the second rule of exception.</div><div> <br /></div>
<div>
<b><span style="font-size: large;">Source code (SuperClassExceptionRule2.java)</span></b>
</div>
<pre class="prettyprint">/**
* Example of SuperClassExceptionRule2 in java.
* @author javaQuery
* @date 2021-09-07
* @Github: https://github.com/javaquery/Examples
*/
public class SuperClassExceptionRule2 {
public void methodWithException() throws IllegalArgumentException{
System.out.println("methodWithException");
}
public static void main(String[] args) {
System.out.printf("SuperClassExceptionRule2");
}
public class ChildClassExceptionRule2 extends SuperClassExceptionRule2 {
// Compile time error when tried to throw parent exception
// @Override
// public void methodWithException() throws Exception{
// super.methodWithException();
// }
// Allowed to throw original exception (IllegalArgumentException)
// or child exception of IllegalArgumentException
@Override
public void methodWithException() throws NumberFormatException{
super.methodWithException();
}
}
public class ChildClassExceptionRule22 extends SuperClassExceptionRule2 {
// Allowed not to throw any exception
@Override
public void methodWithException(){
super.methodWithException();
}
}
}
</pre>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/13775140849340647361noreply@blogger.com0San Francisco Bay Area, CA, USA37.8271784 -122.29130789.5169445638211556 -157.4475578 66.137412236178847 -87.1350578tag:blogger.com,1999:blog-5655258176117800735.post-41907311572375569042021-09-07T17:21:00.002+05:302021-11-01T11:37:47.893+05:30What is the difference between Error and Exception in Java?<div dir="ltr" style="text-align: left;" trbidi="on"></div>
<div class="separator" style="clear: both; text-align: center;"><a href="https://1.bp.blogspot.com/-yCQqcVC6Egg/YTdQC0sPM8I/AAAAAAAAH1Q/Rn0QW4j5oqsZzuoQXavOfHDy6yXXBd6JwCLcBGAsYHQ/s700/Java%2B%252B%2BException.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="300" data-original-width="700" src="https://1.bp.blogspot.com/-yCQqcVC6Egg/YTdQC0sPM8I/AAAAAAAAH1Q/Rn0QW4j5oqsZzuoQXavOfHDy6yXXBd6JwCLcBGAsYHQ/s16000/Java%2B%252B%2BException.png" /></a></div><div dir="ltr" style="text-align: left;" trbidi="on"><br /></div><div dir="ltr" style="text-align: left;" trbidi="on">
Errors and Exceptions are the subclasses of <b>Throwable</b>. However it hold
different context for any Java program. <br />
</div>
<div dir="ltr" style="text-align: left;" trbidi="on"> </div>
<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-size: large;"><b>Errors</b></span> result from failures detected by the Java Virtual Machine, such as
<b class="inlineCode">OutOfMemoryError</b>,
<b class="inlineCode">StackOverflowError</b>, etc... Most simple programs do
not try to handle errors. For errors programs are not expected to recover.
Mostly errors results from lack of resources provided to
program. An Internal error or resource limitation errors are subclasses of <b lass="inlineCode">VirtualMachineError</b>.
</div>
<div dir="ltr" style="text-align: left;" trbidi="on"><br /></div>
<div dir="ltr" style="text-align: left;" trbidi="on">
<b><span style="font-size: large;">Source code (StackOverflowErrorExample.java)</span>
</b><pre class="prettyprint">/**
* Example of StackOverflowError in java.
* @author javaQuery
* @date 2021-09-07
* @Github: https://github.com/javaquery/Examples
*/
public class StackOverflowErrorExample {
private static void recursion(int i){
if(i == 0){
System.out.println("Not reachable code");
}else{
recursion(i++);
}
}
public static void main(String[] args) {
recursion(10);
}
}
</pre>
</div>
<div dir="ltr" style="text-align: left;" trbidi="on">
<b><span style="font-size: large;">Exception</span></b> results when constraints are violated in program.
<a class="externalLink" href="https://www.javaquery.com/2015/05/difference-between-checked-vs-unchecked.html" target="_blank">Exception can be checked exception or unchecked exception</a>. For exceptions, programs are expected to recover. Exception can occur at
compile time (checked exception:
<b class="inlineCode">FileNotFoundException</b>) and at run time (unchecked
exception: <b class="inlineCode">ArithmeticException</b>)<br />
</div>
<div dir="ltr" style="text-align: left;" trbidi="on"><br /></div>
<div dir="ltr" style="text-align: left;" trbidi="on"><b><span style="font-size: large;">Source code (ArithmeticExceptionExample.java)</span>
</b><pre class="prettyprint">/**
* Example of ArithmeticException in java.
* @author javaQuery
* @date 2021-09-07
* @Github: https://github.com/javaquery/Examples
*/
public class ArithmeticExceptionExample {
public static void main(String[] args) {
int x = 10;
int y = getY();
System.out.println(x / y);
}
/**
* This is example of getting value from some method call.
* There is possibilities of getting value `0`.
*
* Java compiler can't identify such errors
*/
public static int getY(){
return 2-2;
}
}
</pre>
</div>
<div dir="ltr" style="text-align: left;" trbidi="on"><br /></div>
<div dir="ltr" style="text-align: left;" trbidi="on"><br /></div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0San Francisco Bay Area, CA, USA37.8271784 -122.29130789.5169445638211556 -157.4475578 66.137412236178847 -87.1350578tag:blogger.com,1999:blog-5655258176117800735.post-18978906879221073322020-06-27T21:26:00.002+05:302021-09-05T18:12:47.076+05:30BiChannelGoogleApi: [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzaq<div>
<a href="https://2.bp.blogspot.com/-0Oj9RD6WCss/V9mM3-i5L9I/AAAAAAAAGMw/0Ujj500X2HAM3A54bAOzRBTv_Dmx4nn4ACLcB/s1600/Firebase%2B%252B%2BGoogle%2B-%2B700x300.png" style="margin-left: 1em; margin-right: 1em;"><img alt="Firebase + Google" border="0" src="https://2.bp.blogspot.com/-0Oj9RD6WCss/V9mM3-i5L9I/AAAAAAAAGMw/0Ujj500X2HAM3A54bAOzRBTv_Dmx4nn4ACLcB/s1600/Firebase%2B%252B%2BGoogle%2B-%2B700x300.png" title="Firebase + Google" /></a>
<br />
<pre class="prettyprint">BiChannelGoogleApi: [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzaq</pre>
One weird exception where Google doesn't show whats wrong with our code or process. I faced same exception and I scratched my head all day long to fix this
issue and finally I fixed it. I'm using phone based Authentication of
Firebase.</div>
<div><br /></div>
<div><b>
Step 1: Enable Firebase logging to see behind whats happening behind the
scene. Add following code in your Main activity class where you are performing authentication.</b><pre class="prettyprint">FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
firebaseDatabase.setLogLevel(Logger.Level.DEBUG);
</pre>
</div>
<div><b>
Step 2: Now you will get the actual error why its not working. In my case I
got following exception.</b><br />
<pre class="prettyprint">com.example W/System.err: com.google.firebase.auth.FirebaseAuthException: This app is not authorized to use Firebase Authentication. Please verify that the correct package name and SHA-1 are configured in the Firebase Console. [ App validation failed ]
com.example W/System.err: at com.google.firebase.auth.api.internal.zzeh.zza(com.google.firebase:firebase-auth@@19.3.1:37)
com.example W/System.err: at com.google.firebase.auth.api.internal.zzfj.zza(com.google.firebase:firebase-auth@@19.3.1:3)
com.example W/System.err: at com.google.firebase.auth.api.internal.zzfm.run(com.google.firebase:firebase-auth@@19.3.1:4)
com.example W/System.err: at android.os.Handler.handleCallback(Handler.java:883)
com.example W/System.err: at android.os.Handler.dispatchMessage(Handler.java:100)
com.example W/System.err: at android.os.Looper.loop(Looper.java:214)
com.example W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7682)
com.example W/System.err: at java.lang.reflect.Method.invoke(Native Method)
com.example W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
com.example W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
com.example E/"TAG": onComplete: Failed=This app is not authorized to use Firebase Authentication. Please verify that the correct package name and SHA-1 are configured in the Firebase Console. [ App validation failed ]
</pre>
</div>
<div><b>
Step 3: I synced Firebase configuration in Android Studio again by Tools
> Firebase > Authentication > Connect > Sync
</b></div>
<div><br /></div>
<div>That's it my exception is no longer there. </div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/13775140849340647361noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-11948534396699337482019-12-10T11:11:00.000+05:302019-12-10T11:11:00.377+05:30How to create immutable class in Java?<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-dcW6KSezV0E/VNGTO2yRPjI/AAAAAAAAF8o/GdoGrnAUiuwVwfJ18QjBLQ26KDCu4PLRgCPcBGAYYCw/s1600/javaQuery_700x300.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="immutable class" border="0" data-original-height="300" data-original-width="700" src="https://1.bp.blogspot.com/-dcW6KSezV0E/VNGTO2yRPjI/AAAAAAAAF8o/GdoGrnAUiuwVwfJ18QjBLQ26KDCu4PLRgCPcBGAYYCw/s1600/javaQuery_700x300.png" title="Immutable class" /></a></div>
<br />
<span style="font-size: large;"><b>Immutable Object</b></span><br />
<div class="blockquote">
Once created its state can not be altered.</div>
String is good example of Immutable class in Java which you use in your day-to-day programming.<br />
<br />
Read: <a class="externalLink" href="https://www.javaquery.com/2014/12/why-string-is-immutable-in-java.html" target="_blank">Why String is immutable in Java?</a><br />
<br />
Most important benefit of immutable class is, It provides thread safety so you don't have to worry about its value getting changed in multi-threaded environment. Also immutable class with valid <b class="inlineCode">hashCode()</b> and <b class="inlineCode">equals()</b> method is good choice for <a class="externalLink" href="https://www.javaquery.com/search/label/Map" target="_blank">Map</a> key.<br />
<br />
Points to be taken care while creating immutable class.<br />
<br />
<ul style="text-align: left;">
<li>Class must be declared as <b class="inlineCode">final</b> so it can not be extended. i.e <b class="inlineCode">public final class ClassName</b>.</li>
<li>All variables/critical methods should be <b class="inlineCode">private</b> so it can not be accessed outside of class. i.e <b class="inlineCode">private int x;</b>.</li>
<li>Make all mutable variables final so it can not be changed after initialization.<br />i.e <b class="inlineCode">private final int x;</b>.</li>
<li>Initialize all variables via constructor only by performing deep copy. (follow example)</li>
<li>Do not provide setter methods for variables. i.e <b class="inlineCode">public void setX(int x) {this.x = x;}</b></li>
<li>Return cloned object/variable in getter method rather returning actual object. (follow example)</li>
</ul>
<br />
<span style="font-size: large;"><b>Source code (ImmutableClassLatLon.java)
</b></span><br />
<pre class="prettyprint">import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Example of Immutable class in java.
* @author javaQuery
* @date 2019-12-10
* @Github: https://github.com/javaquery/Examples
*/
public final class ImmutableClassLatLon {
private final double latitude;
private final double longitude;
private final List<String> labels;
/**
* @param latitude
* @param longitude
* @param labels
*/
public ImmutableClassLatLon(double latitude, double longitude, List<String> labels) {
this.latitude = latitude;
this.longitude = longitude;
if(labels != null && !labels.isEmpty()){
this.labels = new ArrayList<>(labels);
}else{
this.labels = null;
}
}
/**
* Will return new copy of List rather returning reference to current list.
* @return
*/
public List<String> getLabels() {
return labels != null ? new ArrayList<>(labels) : null;
}
/**
* Get new object of ImmutableClassLatLon with updated label.
* @param label
* @return ImmutableClassLatLon
*/
public ImmutableClassLatLon addLabel(String label){
List<String> temporary = new ArrayList<>();
if(labels != null && !labels.isEmpty()){
temporary.addAll(labels);
}
temporary.add(label);
return new ImmutableClassLatLon(latitude, longitude, temporary);
}
public static void main(String[] args) {
ImmutableClassLatLon classLatLon = new ImmutableClassLatLon(23.0225, 72.5714, Arrays.asList("India"));
System.out.println("classLatLon address: " + classLatLon);
System.out.println("\n- classLatLon getLabels and add label -");
System.out.println("classLatLon labels before: " + classLatLon.getLabels());
/* classLatLon.getLabels() will return new copy of List rather returning reference to current list */
List<String> localLables = classLatLon.getLabels();
localLables.add("Hindi");
System.out.println("localLables: " + localLables);
System.out.println("classLatLon labels after: " + classLatLon.getLabels());
System.out.println("\n- add new label to classLatLon -");
System.out.println("classLatLon add label before: " + classLatLon.getLabels());
/* When new label is added it will return new object of ImmutableClassLatLon rather updating current object's list */
ImmutableClassLatLon classLatLonNewLabel = classLatLon.addLabel("Asia");
System.out.println("classLatLon add label after: " + classLatLon.getLabels());
System.out.println("classLatLonNewLabel address: " + classLatLonNewLabel);
System.out.println("classLatLonNewLabel labels: " + classLatLonNewLabel.getLabels());
}
}
</pre>
<span style="font-size: large;"><b>Output</b></span><br />
As you can see after initialization of <b class="inlineCode">ImmutableClassLatLon@36baf30c</b>, user can not change its state even if we provided operation on it.<br />
<pre class="prettyprint">classLatLon address: com.javaquery.core.immutable.ImmutableClassLatLon@36baf30c
- classLatLon getLabels and add label -
classLatLon labels before: [India]
localLables: [India, Hindi]
classLatLon labels after: [India]
- add new label to classLatLon -
classLatLon add label before: [India]
classLatLon add label after: [India]
classLatLonNewLabel address: com.javaquery.core.immutable.ImmutableClassLatLon@7a81197d
classLatLonNewLabel labels: [India, Asia]
</pre>
<span style="font-size: large;"><b>Further Reading</b></span><br />
<a class="externalLink" href="https://www.javaquery.com/2015/06/what-is-difference-between-final-and.html" target="_blank">What is the difference between final and effectively final?</a><br />
<a class="externalLink" href="https://www.javaquery.com/2019/11/how-hashmap-works-internally-in-java.html" target="_blank">How HashMap works internally in Java?</a><br />
<a class="externalLink" href="https://www.javaquery.com/2019/12/how-linkedhashmap-works-internally-in.html" target="_blank">How LinkedHashMap works internally in Java?</a></div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-21689647204002328562019-12-02T13:35:00.000+05:302019-12-02T13:41:27.843+05:30How LinkedHashMap works internally in Java?<div dir="ltr" style="text-align: left;" trbidi="on">
LinkedHashMap implemented using the <a class="externalLink" href="https://www.javaquery.com/search/label/Map?&max-results=10" target="_blank">HashMap</a>. So before we begin to understand How LinkedHashMap works you should first read <a class="externalLink" href="https://www.javaquery.com/2019/11/how-hashmap-works-internally-in-java.html" target="_blank">How HashMap works internally in Java?</a><br />
<br />
We will understand part of code that defers from HashMap and supports LinkedHashMap implementation.<br />
<br />
<span style="font-size: large;"><b>LinkedHasMap#Entry</b></span><br />
Entry class in LinkedHashMap extends Node class of HashMap and contains two more variable <b class="inlineCode">before</b> and <b class="inlineCode">after</b> to hold the before and after references of Entry object.<br />
<pre class="prettyprint">static class Entry<K,V> extends HashMap.Node<K,V> {
Entry<K,V> before, after;
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next);
}
}
</pre>
Now when you <b class="inlineCode">put(key, value)</b> pair in LinkedHashMap, it creates new node object by calling <b class="inlineCode">newNode(..)</b> method. In <b class="inlineCode">newNode(..)</b> method <b class="inlineCode">linkNodeLast(LinkedHashMap.Entry<K,V> p)</b> method is called which is responsible for pointing <b>head</b> and <b>tail</b> element in LinkedHashMap and also set reference of <b>before</b> and <b>after</b> objects.<br />
<pre class="prettyprint">Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
LinkedHashMap.Entry<K,V> p = new LinkedHashMap.Entry<K,V>(hash, key, value, e);
linkNodeLast(p);
return p;
}
private void linkNodeLast(LinkedHashMap.Entry<K,V> p) {
LinkedHashMap.Entry<K,V> last = tail;
tail = p;
if (last == null)
head = p;
else {
p.before = last;
last.after = p;
}
}
</pre>
Following image shows graphical representation of How LinkedHashMap works internally.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-fW_E_QPoc0E/XeDe5AhRZVI/AAAAAAAAGkE/Kh2Pl0U6ibkSezgh9e7i3fM2raciXE-bwCLcBGAsYHQ/s1600/How%2BLinkedHashMap%2Bworks.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="510" data-original-width="702" src="https://1.bp.blogspot.com/-fW_E_QPoc0E/XeDe5AhRZVI/AAAAAAAAGkE/Kh2Pl0U6ibkSezgh9e7i3fM2raciXE-bwCLcBGAsYHQ/s1600/How%2BLinkedHashMap%2Bworks.png" /></a></div>
<br />
Lets understand LinkedHashMap implementation using real Java Program to make everything clear.<br />
<br />
<span style="font-size: large;"><b>Source code (LinkedHashMapExample.java)</b></span><br />
<b>Note</b>: Check value of <b class="inlineCode">before</b>, <b class="inlineCode">after</b> and <b class="inlineCode">next</b> to understand example.
<br />
<pre class="prettyprint">import java.util.LinkedHashMap;
import java.util.Map;
/**
* LinkedHashMap Example.
* @author javaQuery
* @date 2019-11-29
* @Github: https://github.com/javaquery/Examples
*/
public class LinkedHashMapExample {
public static void main(String[] args) {
Map<String, String> map = new LinkedHashMap<>();
/* Check value of before, after and next to understand example */
map.put("AaAaAa", "JJJ");
/**
* Current bucket data visualization
*
* bucket-index: 2
* EntryObject1 [before = null, hash = 123, key = AaAaAa, value = JJJ, next = null, after = null]
*/
map.put("xyz", "KKK");
/**
* Current bucket data visualization
*
* bucket-index: 2
* EntryObject1 [before = null, hash = 123, key = AaAaAa, value = JJJ, next = null, after = EntryObject2]
*
* bucket-index: 11
* EntryObject2 [before = EntryObject1, hash = 456, key = xyz, value = KKK, next = null, after = null]
*/
/* since hashcode of 'AaAaBB' is same as 'AaAaAa' so it be added at 2nd index in bucket */
map.put("AaAaBB", "LLL");
/**
* Current bucket data visualization
*
* bucket-index: 2
* [
* EntryObject1 [before = null, hash = 123, key = AaAaAa, value = JJJ, next = EntryObject3, after = EntryObject2]
* EntryObject3 [before = EntryObject2, hash = 123, key = AaAaBB, value = LLL, next = null, after = null]
* ]
*
* bucket-index: 11
* EntryObject2 [before = EntryObject1, hash = 456, key = xyz, value = KKK, next = null, after = EntryObject3]
*/
}
}
</pre>
Above program can be graphically represented as follows.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-mOhpIcXARJ0/XeDe-ASgfWI/AAAAAAAAGkI/2RHCSzuLy04HkAKXmU39n2dp_D_gMFIhACLcBGAsYHQ/s1600/LinkedHashMap%2Bdata%2Bvisualization.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="363" data-original-width="1055" src="https://1.bp.blogspot.com/-mOhpIcXARJ0/XeDe-ASgfWI/AAAAAAAAGkI/2RHCSzuLy04HkAKXmU39n2dp_D_gMFIhACLcBGAsYHQ/s1600/LinkedHashMap%2Bdata%2Bvisualization.png" /></a></div>
<br />
<span style="font-size: large;"><b>References</b></span><br />
<a class="externalLink" href="https://www.javaquery.com/2019/11/how-hashmap-works-internally-in-java.html" target="_blank">How HashMap works internally in Java?</a><br />
<a class="externalLink" href="https://www.javaquery.com/2019/11/popular-map-interview-questions-in-java.html" target="_blank">Popular Map interview questions in Java</a></div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-6910107853878884112019-11-28T10:53:00.001+05:302019-12-02T13:37:48.122+05:30Popular Map interview questions in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<b>Question</b>: Why Map interface does not extends Collection interface?<br />
<b>Answer</b>: <b>Map</b> is (key, value) pair not a collection of one type of values so it does not extends <b>Collection</b> interface. <b>Collection</b> interface accept single object via <b class="inlineCode">add(E e)</b> but <b>Map</b> interface requires key, value pair in method <b class="inlineCode">put(K key, V value)</b><br />
<br />
<b>Question</b>: Does Map accept `null` as key?<br />
<b>Answer</b>: HashMap and LinkedHashMap accepts null key but TreeMap will throws <b class="inlineCode">NullPointerException</b>. HashMap stores null key at 0th index in bucket.<br />
<br />
<b>Question</b>: Does Map accept `null` values?<br />
<b>Answer</b>: You can have <b class="inlineCode">n</b> null values.<br />
<br />
<b>Question</b>: What is the initial capacity of HashMap?<br />
<b>Answer</b>: 16. <b class="inlineCode">DEFAULT_INITIAL_CAPACITY = (1 << 4)</b><br />
<br />
<b>Question</b>: What is the maximum capacity of HashMap?<br />
<b>Answer</b>: 1073741824. <b class="inlineCode">MAXIMUM_CAPACITY = ( 1 << 30)</b><br />
<br />
<b>Question</b>: Does HashMap maintain insertion order?<br />
<b>Answer</b>: No<br />
<br />
<b>Question</b>: Is HashMap synchronized?<br />
<b>Question</b>: Is HashMap thread-safe?<br />
<b>Answer</b>: No<br />
<br />
<b>Question</b>: How to synchronize Map?<br />
<b>Answer</b>: Using <b class="inlineCode">Collections.synchronizedMap(map)</b>, best practice <b class="inlineCode">Map m = Collections.synchronizedMap(new HashMap(...));</b><br />
<br />
<b>Question</b>: How to avoid concurrent modification exception?<br />
<b>Answer</b>: Synchronize Map using <b class="inlineCode">Map m = Collections.synchronizedMap(new HashMap(...));</b> or <b class="inlineCode">Map n = new ConcurrentHashMap();</b><br />
<br />
<b>Question:</b> How HashMap works internally in Java?<br />
<b>Answer</b>: To understand How HashMap works internally read the article <a class="externalLink" href="https://www.javaquery.com/2019/11/how-hashmap-works-internally-in-java.html" target="_blank">https://www.javaquery.com/2019/11/how-hashmap-works-internally-in-java.html</a><br />
<br />
<b>Question</b>: What happens when you put same key again in HashMap?<br />
<b>Answer</b>: When you put(existing-key, value) in HashMap, it will replace old value with new value. And returns old value.<br />
<pre class="prettyprint">Map<String, String&gt; map = new HashMap<&gt;();
map.put("a", "x");
String oldValue = map.put("a", "y");
System.out.println(oldValue);
//output: x
</pre>
<br />
<b>Question</b>: Can we store duplicate key in HashMap?<br />
<b>Answer</b>: No<br />
<br />
<b>Question</b>: Can we store duplicate value in HashMap?<br />
<b>Answer</b>: Yes.<br />
<br />
<b>Question</b>: What is Hash code/key collision?<br />
<b>Answer</b>: When two same or different hash code of key generates same index of bucket location by performing bitwise AND is called hash code/key collision. In this situation HashMap forms linked list at given bucket location (index).<br />
<br />
For example <b class="inlineCode">"AaAaAa".hashCode()</b> and <b class="inlineCode">"AaAaBB".hashCode()</b> generates same hash code.<br />
<br />
<b>Question</b>: How HashMap handles Hash code/key collision?<br />
<b>Question</b>: What will happens if two objects have same hash code?<br />
<b>Answer</b>: It forms linked list at bucket location.<br />
<br />
<b>Question</b>: Why String, Integer and other wrapper classes are good choice for HashMap key?<br />
<b>Answer</b>: String, Integer and other wrapper classes are immutable so its best choice to use it as key. <a class="externalLink" href="https://www.javaquery.com/2014/12/why-string-is-immutable-in-java.html" target="_blank">Why String is immutable in Java?</a><br />
<br />
<b>Question</b>: Can we use mutable key in HashMap?<br />
<b>Answer</b>: Yes, You can use mutable key but its not good choice because it'll fail to retrieve correct value in get(key).<br />
<br />
<b>Question</b>: Can we use our own custom object/class as key in HashMap?<br />
<b>Answer</b>: Yes, You can use your custom object as key in HashMap but its necessary to consider immutability of that object and also implementing hashCode() and equals() method in your class.<br />
<br />
<b>Question</b>: How HashMap is improved in Java 8?<br />
<b>Answer</b>: Prior to Java 8, HashMap forms linked list in case of hash collision. Now from Java 8 when hash collision occurs and it hits following threshold <b>TREEIFY_THRESHOLD = 8</b> and <b>MIN_TREEIFY_CAPACITY = 64</b> then it uses TreeNode to store Entry object to improve HashMap get performance.<br />
<a class="externalLink" href="https://stackoverflow.com/questions/58987907/why-hashmap-resize-when-it-hits-treeify-threshold-value-which-is-not-required/58990202#58990202" target="_blank">Why HashMap resize when it hits TREEIFY_THRESHOLD value which is not required?</a><br />
<br />
<b>Question</b>: Which tree stucture is used in Java 8 to improve performance of HashMap?<br />
<b>Answer</b>: red-black tree structure is used to improce performance of HashMap.<br />
<br />
<b>Question</b>: How LinkedHashMap works internally in Java?<br />
<b>Answer</b>: To understand How LinkedHashMap works internally read the article <a class="externalLink" target="_blank" href="https://www.javaquery.com/2019/12/how-linkedhashmap-works-internally-in.html">https://www.javaquery.com/2019/12/how-linkedhashmap-works-internally-in.html</a> <br/><br/></div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-14848860143122787302019-11-27T12:21:00.002+05:302019-12-02T14:09:05.917+05:30How HashMap works internally in Java?<div dir="ltr" style="text-align: left;" trbidi="on">
HashMap is one of the implementation of <b class="inlineCode">java.util.Map</b> interface. We will understand how it internally stores (put) and retrieve (get) values. HashMap uses array known as bucket/table to store (key, value) pair.<br />
<br />
This is one of the popular question in Java <a class="externalLink" href="https://www.javaquery.com/search/label/Interview" target="_blank">Interviews</a>, lets understand how it works. <br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<span style="font-size: large;"><b>Instantiation: How to create HashMap object?</b></span><br />
There are 3 different ways you instantiate HashMap<br />
<br />
<ol style="text-align: left;">
<li>new HashMap() - It will create HashMap with default capacity of 16 and default load factor 0.75f.</li>
<li>new HashMap(int initialCapacity) - You can provide the initial capacity of HashMap and default load factor 0.75f is used.</li>
<li>new HashMap(int initialCapacity, float loadFactor) - You can provide both initial capacity and load factor.</li>
</ol>
<b>Note</b>: We will consider HashMap with default capacity and load factor for explanation of this article.<br />
<br />
<span style="font-size: large;"><b>Understanding implementation of HashMap</b></span><br />
I extracted Node class (inner class) from HashMap which implements sub-interface <b>Entry</b> of <a class="externalLink" href="https://www.javaquery.com/search/label/Map" target="_blank"><b>Map</b></a> interface. Node class plays important role in implementation of HashMap. Every (key, value) pair in HashMap will be stored as <b>Entry</b> object <b>using Node class implementation</b>.<br />
<br />
Node class holds - <b>hash code of key</b>, <b>key</b>, <b>value</b> and `<b>next</b>` is used to store next element (node) reference in case of hash code/key collision. We'll understand hash code/key collision later in this article.<br />
<pre class="prettyprint">static class Node<K,V> implements Map.Entry<K,V> {
final int hash; // hash code of key
final K key; // the key
V value; // the value to put
Node<K,V> next; // next element(node) in case of hash code/key collision
Node(int hash, K key, V value, Node<K,V> next) {...}
...
...
}</pre>
<br />
<span style="font-size: large;"><b>What happens when you put(K key, V value) in HashMap?</b></span><br />
When you put (key, value) pair in HashMap, it generates hash of key by calling <b class="inlineCode">hashCode()</b> method of key and follows these steps...<br />
<br />
<ul style="text-align: left;">
<li><a class="externalLink" href="https://www.blogger.com/blogger.g?blogID=5655258176117800735#1.1" id="1.1"><b>put#1.1:</b></a> Create the bucket (array) of <b class="inlineCode">Node<K, V>[]</b> with default capacity or given capacity if not initialized. </li>
<ul>
<li>In case of bucket (array) is full then it increases capacity by twice the current capacity and transfer all data to new bucket (array). (i.e default capacity [16] > [32] > [64] ...)</li>
</ul>
<li>
<a class="externalLink" href="https://www.blogger.com/blogger.g?blogID=5655258176117800735#1.2" id="1.2"><b>put#1.2:</b></a> Now it generates bucket location (array-index) by performing bitwise AND on current capacity of bucket and hash code of key
<pre class="prettyprint">/**
* i = index to store (key, pair) in bucket (array)
* n = size of bucket (array)
* hash = hash code of key
*/
int i = (n - 1) & hash;
</pre>
</li>
<li><a class="externalLink" href="https://www.blogger.com/blogger.g?blogID=5655258176117800735#1.3" id="1.3"><b>put#1.3:</b></a>
Fetch node (element) from bucket using generated location (index).</li>
<ul>
<li><a class="externalLink" href="https://www.blogger.com/blogger.g?blogID=5655258176117800735#1.3.1" id="1.3.1"><b>put#1.3.1:</b></a> no element found - insert given key, pair in form of Node object (Entry object).</li>
<li><a class="externalLink" href="https://www.blogger.com/blogger.g?blogID=5655258176117800735#1.3.2" id="1.3.2"><b>put#1.3.2:</b></a> element found at that location (index) - its the case of Hash code/key collision.</li>
<ul>
<li><a class="externalLink" href="https://www.blogger.com/blogger.g?blogID=5655258176117800735#1.3.2.1" id="1.3.2.1"><b>put#1.3.2.1:</b></a> Now it'll compare key of existing node (element) with newly given key. If both the keys are same then it'll replace current Node's value with new value.</li>
<li><a class="externalLink" href="https://www.blogger.com/blogger.g?blogID=5655258176117800735#1.3.2.2" id="1.3.2.2"><b>put#1.3.2.2:</b></a> If both the keys are different then it forms linked list at the bucket location (index). Current node's <b>next </b>variable will be assigned to reference of newly given Node (key, value). </li>
</ul>
</ul>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-7qlGiyxNuGc/Xd0UQjr3jBI/AAAAAAAAGj8/VqXHcWZ_WYUv13QLBzbIOBRv2bXL3Wn6ACPcBGAYYCw/s1600/How%2BHashMap%2BWorks%2BInternally%2Bin%2BJava.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="352" data-original-width="720" src="https://1.bp.blogspot.com/-7qlGiyxNuGc/Xd0UQjr3jBI/AAAAAAAAGj8/VqXHcWZ_WYUv13QLBzbIOBRv2bXL3Wn6ACPcBGAYYCw/s1600/How%2BHashMap%2BWorks%2BInternally%2Bin%2BJava.png" /></a></div>
<br />
<br />
<span style="font-size: large;"><b>What happens when you get(Object key) in HashMap?</b></span><br />
When you try to get value using key, it generates hash of key by calling <b class="inlineCode">hashCode()</b> method of key and follows these steps...<br />
<br />
<ul style="text-align: left;">
<li><a class="externalLink" href="https://www.blogger.com/blogger.g?blogID=5655258176117800735#get1.1" id="get1.1"><b>get#1.1</b></a>: Generates bucket location (array-index) by performing bitwise AND on current capacity of bucket and hash code of key.</li>
<li><a class="externalLink" href="https://www.blogger.com/blogger.g?blogID=5655258176117800735#get1.2" id="get1.2"><b>get#1.2</b></a>: Find the Entry(Node) object from that bucket index.</li>
<ul>
<li><a class="externalLink" href="https://www.blogger.com/blogger.g?blogID=5655258176117800735#get1.2.1" id="get1.2.1"><b>get#1.2.1</b></a>: No Entry object found - returns null. </li>
<li><a class="externalLink" href="https://www.blogger.com/blogger.g?blogID=5655258176117800735#get1.2.2" id="get1.2.2"><b>get#1.2.2</b></a>: Entry object found from bucket - It will compare provided <b>hash of key</b>, <b>key</b> and calls <b>equals()</b> method of key with Entry object found from bucket. </li>
<ul>
<li><a class="externalLink" href="https://www.blogger.com/blogger.g?blogID=5655258176117800735#get1.2.2.1" id="get1.2.2.1"><b>get#1.2.2.1</b></a>: If everything matched then it returns the Entry object. </li>
<li><a class="externalLink" href="https://www.blogger.com/blogger.g?blogID=5655258176117800735#get1.2.2.2" id="get1.2.2.2"><b>get#1.2.2.2</b></a>: If not matched then it check linked list formed at that bucket location (has `next` element) then do the same check as in <a class="externalLink" href="https://www.blogger.com/blogger.g?blogID=5655258176117800735#get1.2.2" id="get1.2.2"><b>get#1.2.2</b></a> until it find the correct Entry object from linked list.</li>
</ul>
</ul>
</ul>
Now lets discuss question can be asked in <a class="externalLink" href="https://www.javaquery.com/search/label/Interview" target="_blank">interview</a> related to implementation.<br />
<br />
<span style="font-size: large;"><b>What is the initial capcity and load factor of HashMap?</b></span><br />
Initial capacity of HashMap is 16 and load factor is 0.75f.<br />
<br />
<span style="font-size: large;"><b>How HashMap stores data in bucket (array/table)?</b></span><br />
Its important to remember that HashMap stores not just hash code of key in Array. It stores hash code, key, value and `next` as Entry object in Array.<br />
<br />
<span style="font-size: large;"><b>What is Hash code/key collision?</b></span><br />
When two <b>same or different</b> hash code of key generates same index of bucket location by performing <b>bitwise AND</b> is called hash code/key collision. In this situation HashMap forms linked list at given bucket location (index).<br />
<br />
For example <b>"AaAaAa".hashCode()</b> and <b>"AaAaBB".hashCode()</b> generates same hash code.<br />
<br />
<b><span style="font-size: large;">How HashMap handles Hash code/key collision?</span></b><br />
<b><span style="font-size: large;">What will happend if two objects have same hash code? </span></b><br />
It forms linked list at bucket location.<br />
<br />
<span style="font-size: large;"><b>How HashMap will retrieve value when two keys have same hash code?</b></span><br />
Linked list formed at bucket location when two keys have same hash code so it'll travese through all linked list node until it find the correct key and equals method of key retruns true. Read <a class="externalLink" href="https://www.blogger.com/blogger.g?blogID=5655258176117800735#get1.2.2">get1.2.2</a> for complete understanding.<br />
<br />
<span style="font-size: large;"><b>Where does HashMap stores null key?</b></span><br />
null key will be stored at 0th index of bucket.<br />
<br />
<span style="font-size: large;"><b>Why String, Integer and other wrapper classesare good choice for HashMap key?</b></span><br />
String, Integer and other wrapper classes are immutable so its best choice to use it as key. <a class="externalLink" href="https://www.javaquery.com/2014/12/why-string-is-immutable-in-java.html" target="_blank">Why String is immutable in Java?</a><br />
<br />
<span style="font-size: large;"><b>Can we use mutable key in HashMap?</b></span><br />
Yes, You can use mutable key but its not good choice because it'll fail to retrive correct value in get(key).<br />
<br />
<span style="font-size: large;"><b>Can we use our own custom object as key in HashMap?</b></span><br />
Yes, You can use your custom object as key in HashMap but its necessary to consider immutablity of that object and also implementing <b>hashCode()</b> and <b>equals()</b> method in your class. <br />
<br />
<span style="font-size: large;"><b>How HashMap is improved in Java 8?</b></span><br />
Prior to Java 8, HashMap forms linked list in case of hash collision. Now from Java 8 when hash collision occurs and it hits following threshold <b class="inlineCode">TREEIFY_THRESHOLD = 8</b> and <b class="inlineCode">MIN_TREEIFY_CAPACITY = 64</b> then it uses TreeNode to store Entry object to improve HashMap get performance.<br />
<a class="externalLink" href="https://stackoverflow.com/questions/58987907/why-hashmap-resize-when-it-hits-treeify-threshold-value-which-is-not-required/58990202#58990202" target="_blank">Why HashMap resize when it hits TREEIFY_THRESHOLD value which is not required?</a><br />
<br />
<span style="font-size: large;"><b>Which tree stucture is used in Java 8 to improve performance of HashMap?</b></span><br />
red-black tree structure is used to improce performance of HashMap.<br />
<br />
<span style="font-size: large;"><b>References</b></span><br />
<a class="externalLink" href="https://www.javaquery.com/2019/11/popular-map-interview-questions-in-java.html" target="_blank">Popular Map interview questions in Java</a><br />
<a class="externalLink" href="https://www.javaquery.com/2019/12/how-linkedhashmap-works-internally-in.html" target="_blank">How LinkedHashMap works internally in Java?</a><br />
<br /></div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-70227992452918601622019-11-15T14:07:00.004+05:302019-11-15T14:13:18.165+05:30What is Abstract class in Java and popular interview questions?<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-size: large;"><b>What is Abstract Class? </b></span><br />
An abstract class is a class that is incomplete, or to be considered incomplete.<br />
<br />
You can declare <i>abstract</i> methods for which non abstract subclass has to provide implementation or it'll give compile-time error. "Methods that are declared but not yet implemented."<br />
<br />
Also you can provide method implementation in <i>abstract</i> class itself. It can be used from subclass. You can override these method in its subclass.<br />
<br />
<span style="font-size: large;"><b>Source code (Mobile.java)</b></span><br />
<pre class="prettyprint">import java.util.Date;
public abstract class Mobile {
/**
* Sub class has to provide implementation for method `call()`
*/
public abstract void call();
/**
* Sub class has to provide implementation for method `sms()`
*/
public abstract void sms();
/**
* We've provided implementation for current time.
*/
public Date currentTime(){
return new Date();
}
}
</pre>
<span style="font-size: large;"><b>Source code (SmartMobile.java)</b></span>
<br />
<pre class="prettyprint">public class SmartMobile extends Mobile{
public void call(){
// provide implementation
}
public void sms(){
// provide implementation
}
}
</pre>
<span style="font-size: large;"><b>Source code (Main.java)</b></span>
<br />
<pre class="prettyprint">public class Main(){
public static void main(String[] args){
/** You can not instantiate abstract class.
* Following line will cause Compile-Time error
*/
// Mobile mobile = new Mobile();
Mobile smartMobile = new SmartMobile();
}
}
</pre>
<br />
Now lets discuss behavior of <i>abstract</i> class via question-answer. These are the popular <i>abstract</i> class interview questions .<br />
<br />
<b>Question:</b> Can we instantiate <i>abstract</i> class?<br />
<b>Answer:</b> No. We can not instantiate <i>abstract</i> class. Its restricted by Java.<br />
<br />
<b>Question:</b> Why does <i>abstract</i> class have constructor if we can not instantiate?<b> </b><br />
<b>Answer:</b> Constructor in <i>abstract</i> class used to initialize properties/fields of <i>abstract</i> class via not abstract sub-class.<br />
<br />
<b>Question:</b> When constructor of <i>abstract</i> class called?<br />
<b>Answer:</b> When sub-class instantiated, constructor of <i>abstract</i> class is called.<br />
<br />
<b>Question:</b> Can we mark constructor as <i>abstract</i>?<br />
<b>Answer:</b> No<br />
<br />
<b>Question:</b> Is it compulsory for <i>abstract</i> class to have at least one <i>abstract</i> method?<br />
<b>Answer:</b> No its not compulsory. You can create <i>abstract</i> class <b>with or without</b> <i>abstract</i> methods.<br />
<br />
<b>Question:</b> Can we declare <i>abstract</i> method as private?<b> </b><br />
<b>Answer:</b> No. If abstract method is private then its not visible/accessible in its sub-class so it can not provide its implementation. However you can make <i>abstract</i> method protected.<br />
<br />
<b>Question:</b> Why final and <i>abstract</i> can not be used at a time?<b> </b><br />
<b>Answer:</b> When class or method marked with <i>final</i> means value or implementation provided and you don't want it to be changed while <i>abstract</i> means implementation asked to provide.<br />
<br />
Simply it contradicts with each other.<br />
<br />
<b>Question:</b> Can we declare <i>abstract</i> class or method as static?<br />
<b>Answer:</b> No. static can be called without creating object and it contains implementation or value. <i>abstract</i> means implementation asked to provide. Its same as final.<br />
<br />
Simply it contradicts with each other.<br />
<br />
<b>Question:</b> Can we declare inner class as <i>abstract</i>?<br />
<b>Answer:</b> Yes<br />
<br />
<b>Question:</b> Can <i>abstract</i> method include throws in its declaration?<br />
<b>Answer:</b> Yes <br />
<br />
<b>Question:</b> Can we mark <i>abstract</i> method as synchronized?<br />
<b>Answer:</b> No. However sub-class which override the method can be synchronized.<br />
<pre class="prettyprint">public abstract class Demo{
public abstract void test();
}
public class DemoImpl extends Demo{
@Override
public synchronized void test(){
//implementation
}
}
</pre>
<br />
<b>Question:</b> Can we use <i>abstract</i> class as member of another <i>abstract</i> class?<br />
<b>Answer:</b> Yes. Its same as declaring other class as member(variable).<br />
<br />
<span style="font-size: large;"><b>Reference</b></span><br />
<a class="externalLink" href="https://www.javaquery.com/2015/02/difference-between-abstract-class-and.html" target="_blank">Difference between Abstract class and Interface in Java</a><br />
<br /></div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-49422389042942660572019-11-10T18:43:00.001+05:302019-11-10T18:46:54.490+05:30How to run MySQL Server in docker?<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-Xdnpgn1QIf8/XcgL5yUo4XI/AAAAAAAAGi0/4Ir9UXaxNwE91Tkgkjy4cb0xWMOTyMuxQCLcBGAsYHQ/s1600/MySQL%2Bin%2BDocker.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="MySQL in Docker" border="0" data-original-height="300" data-original-width="700" src="https://1.bp.blogspot.com/-Xdnpgn1QIf8/XcgL5yUo4XI/AAAAAAAAGi0/4Ir9UXaxNwE91Tkgkjy4cb0xWMOTyMuxQCLcBGAsYHQ/s1600/MySQL%2Bin%2BDocker.png" title="MySQL in Docker" /></a></div>
<br />
In my previous article we understood <a class="externalLink" target="_blank" href="https://www.javaquery.com/2019/11/why-docker-and-what-is-docker.html" target="_blank">Why Docker and What is Docker?</a> Now lets see how you launch MySQL in Docker.<br />
<br />
<span style="font-size: large;"><b>Prerequisite</b></span><br />
Docker must be installed in your local system.<br />
<br />
<b>Step 1:</b> Open terminal in root mode. Launch MySQL by following command. It'll download MySQL DockerImage if not available and then start it.
<br />
<pre class="prettyprint">root@vicky:/home/vicky# docker run --name localmysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=root -d mysql
Unable to find image 'mysql:latest' locally
latest: Pulling from library/mysql
6ae821421a7d: Pull complete
a9e976e3aa6d: Pull complete
e3735e44a020: Pull complete
bfd564e9483f: Pull complete
df705f26e488: Pull complete
0c5547f73d62: Pull complete
f437382cf8a1: Pull complete
b8e2d50f1513: Pull complete
e2e3c9928180: Pull complete
b60db6d282cd: Pull complete
1d32deab69c6: Pull complete
408a40cd2e9c: Pull complete
Digest: sha256:a571337738c9205427c80748e165eca88edc5a1157f8b8d545fa127fc3e29269
Status: Downloaded newer image for mysql:latest
89911662a4793d0468427919d395535e05a3b3004aeb8173cd4d9eaede30fa3a
</pre>
<b>Step 2:</b> Verify MySQL is running or not by executing following command.
<br />
<pre class="prettyprint">root@vicky:/home/vicky# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
89911662a479 mysql "docker-entrypoint..." 6 minutes ago Up 6 minutes 0.0.0.0:3306->3306/tcp, 33060/tcp localmysql
</pre>
<b>Step 3:</b> Enter into Docker MySQL app by executing following command.
<br />
<pre class="prettyprint">root@vicky:/home/vicky# docker exec -ti localmysql bash
</pre>
<b>Step 4:</b> You are into MySQL app. You can now connect and execute to MySQL commands on it.
<br />
<pre class="prettyprint">root@89911662a479:/# mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.15 MySQL Community Server - GPL
Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> ALTER USER 'root' IDENTIFIED WITH mysql_native_password BY 'root';
Query OK, 0 rows affected (0.05 sec)
mysql> CREATE DATABASE javaquery;
Query OK, 1 row affected (0.08 sec)
mysql> use javaquery;
Database changed
mysql> CREATE TABLE demo(id int, name varchar(100), email varchar(250));
Query OK, 0 rows affected (0.19 sec)
mysql> INSERT INTO demo(id, name, email) values(1, 'Vicky Thakor', 'vicky.thakor@javaquery.com');
Query OK, 1 row affected (0.05 sec)
mysql> SELECT * FROM demo;
+------+--------------+----------------------------+
| id | name | email |
+------+--------------+----------------------------+
| 1 | Vicky Thakor | vicky.thakor@javaquery.com |
+------+--------------+----------------------------+
1 row in set (0.00 sec)
mysql> exit
Bye
</pre>
<b>Step 5:</b> Exit from container
<br />
<pre class="prettyprint">root@89911662a479:/# exit
exit
</pre>
<b>Step 6:</b> Stop MySQL container
<br />
<pre class="prettyprint">root@vicky:/home/vicky# docker container stop localmysql
localmysql
</pre>
<b>Step 7:</b> Remove MySQL container from docker engine.
<br />
<pre class="prettyprint">root@vicky:/home/vicky# docker container rm localmysql
localmysql
</pre>
<b>Step 8:</b> List docker images.
<br />
<pre class="prettyprint">root@vicky:/home/vicky# docker images -a
REPOSITORY TAG IMAGE ID CREATED SIZE
mysql latest 81f094a7e4cc 47 hours ago 477MB
</pre>
<b>Step 9:</b> Remove MySQL completely from Docker.
<br />
<pre class="prettyprint">root@vicky:/home/vicky# docker rmi 81f094a7e4cc
Untagged: mysql:latest
Untagged: mysql@sha256:a571337738c9205427c80748e165eca88edc5a1157f8b8d545fa127fc3e29269
Deleted: sha256:81f094a7e4ccc963fde3762e86625af76b6339924bf13f1b7bd3c51dbcfda988
Deleted: sha256:77dac193858f3954c3997272aabbad794166770b735ea18c313cd920c6f9ae56
Deleted: sha256:29c7593e2c24df6b8a0c73c4445dce420a41801bb28f1e207c32d7771dfb2585
Deleted: sha256:5b0034d0389c5476c01ad2217fc3eddfcceb7fb71489fa266aac13c28b973bb5
Deleted: sha256:a8380edd959f5f457dfaff93b58bd9926cd7226fc7cfade052459bcaecf5404b
Deleted: sha256:75082d1a98ce7ef9eb053ed89644e09c38b4ebd6c964ec3eb050c637480a2874
Deleted: sha256:afa9c09812bcbc0960c0db6d5c1b3af6286097935e4aa46153b4538ad7082e4f
Deleted: sha256:7d3a170fc2a4187c57e941e4f37913add9034ac7e44f658630d38bc617b673b9
Deleted: sha256:1414c04de349b69ee9d1a593d766a275b92b1a01e4c440092ccde60b1ff8e5d9
Deleted: sha256:bcf08b24b02cc14c6a934d7279031a3f50bc903d903a2731db48b8cb6a924300
Deleted: sha256:81b6eebc1d362d1ca2a888172e315c4e482e0e888e4de4caef3f9e29a3339b78
Deleted: sha256:2c5c6956c8c5752b2034f6ab742040b574d9e3598fbd0684d361c8fc9ccb3554
Deleted: sha256:0a07e81f5da36e4cd6c89d9bc3af643345e56bb2ed74cc8772e42ec0d393aee3
</pre>
</div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-38699815163045038732019-11-10T18:11:00.000+05:302019-11-10T18:46:34.815+05:30Why Docker and What is Docker?<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-j9DA-QgceWY/Xcf8D-637DI/AAAAAAAAGio/C_3_VjVxyoA2nS5DRBYV8tipC9563AoYQCLcBGAsYHQ/s1600/Docker%2BLogo.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="docker logo" border="0" data-original-height="300" data-original-width="700" src="https://1.bp.blogspot.com/-j9DA-QgceWY/Xcf8D-637DI/AAAAAAAAGio/C_3_VjVxyoA2nS5DRBYV8tipC9563AoYQCLcBGAsYHQ/s1600/Docker%2BLogo.png" title="Docker Logo" /></a></div>
<br />
<span style="font-size: large;"><b>Why Docker?</b></span><br />
As a developer, Have you ever run into situations like...<br />
<br />
<ul style="text-align: left;">
<li>Code is working in local system, ain't working on production/staging server.</li>
<li>Software(apache, php, etc...) upgrade on production/staging server crashed your code.</li>
<li>Require separate environment of your website/server to test newly developed feature.</li>
</ul>
All these problems of Software Development Life Cycle (SDLC) can be solved by docker. Now lets see...<br />
<br />
<span style="font-size: large;"><b>What is Docker?</b></span><br />
Docker is like virtual machine but unlike virtual machine, docker don't need separate Operating System on top of Host Operating System. Docker uses Host Operating System directly via Docker Engine to run applications.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-NoQXypOHsow/Xcf6e_hSzDI/AAAAAAAAGic/OFSGHXnLdPMwjWkpz6WF5TpIHCe1hUfmQCLcBGAsYHQ/s1600/Docker%2BContainers%2Bvs%2BVirtual%2BMachines.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Docker Containers vs Virtual Machines" border="0" data-original-height="435" data-original-width="1024" height="271" src="https://1.bp.blogspot.com/-NoQXypOHsow/Xcf6e_hSzDI/AAAAAAAAGic/OFSGHXnLdPMwjWkpz6WF5TpIHCe1hUfmQCLcBGAsYHQ/s640/Docker%2BContainers%2Bvs%2BVirtual%2BMachines.png" title="Docker Containers vs Virtual Machines" width="640" /></a></div>
<br />
<b><span style="font-size: large;">How Software Development Life Cycle (SDLC) problems can be solved?</span></b><br />
Using DockerFile, write your application specific environment to run.<br />
<br />
<span style="font-size: large;"><b>What is DockerFile?</b></span><br />
File contains environment specific configuration like: for development, for testing, for production, for release_v2.3.1, etc... This can be further drilled down as per your micro-services like...<br />
<br />
<ul style="text-align: left;">
<li>dev-inventory-ui-php</li>
<li>dev-inventory-backend-java</li>
<li>dev-salesorder-ui-react</li>
<li>dev-salesorder-backend-spring </li>
</ul>
<br />
<span style="font-size: large;"><b>DockerFile</b></span><br />
<span style="font-size: large;"><span style="font-size: small;">Sample docker file. No extension is required for this file.</span><b> </b></span><br />
<pre class="prettyprint">FROM openjdk:8-jre
VOLUME /tmp
ADD your-app-main-1.0.jar destination-file-docker-app.jar
ENV JAVA_OPTS=""
ENTRYPOINT exec java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /destination-file-docker-app.jar
</pre>
<span style="font-size: large;"><b>Docker in action</b></span><br />
On local system you developed your application with Java version 8 now specify same version in <b>DockerFile</b>. Image built/created from this <b>DockerFile</b> will run Java version 8 in Container. So application will work as expected.<br />
<br />
Now say if you upgrade your code for Java version 9. All you need to do is just update your DockerFile's Java version to 9. Docker will check that Java version 9 is needed and not available so it'll download Java version 9 and then run your application.<br />
<br />
Lets say something goes wrong then you can launch container from your previous <b>DockerImage</b> of Java version 8. And you application is downgraded, no need to uninstall Java version 9 or any other software you added with new <b>DockerFile</b>.<br />
<br />
By just writing <b>DockerFile</b> you can control your application's execution environment from <b>local to development</b> and <b>development to production</b>. You can also create multiple <b>DockerFile</b> for different environments as per your requirements.<br />
<br />
<ul style="text-align: left;">
<li>Code execution will be same as local for production server.</li>
<li>This way you don't need to worry about upgrading/downgrading your server's environment.</li>
<li>Also same <b>DockerImage</b> can be used to launch new service. Docker will download all required software on server that are mentioned <b>DockerFile</b>. No overhead of configuring server for launching new service.</li>
</ul>
<br />
<span style="font-size: large;"><b>Advantages of Docker</b></span><br />
<br />
<ul style="text-align: left;">
<li>Light weight compare to virtual machine.</li>
<li>Same <b>DockerImage</b> can run on local, Kubernetes, Amazon Web Service, Google Cloud, Microsoft Azure or any other cloud platform without changing anything in <b>DockerFile</b>.</li>
<li>Quickly start your application in Docker.</li>
</ul>
<br />
<span style="font-size: large;"><b>Other References:</b></span><br />
<a class="externalLink" href="https://www.javaquery.com/2019/11/how-to-run-mysql-server-in-docker.html" target="_blank">How to run MySQL Server in docker?</a></div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-19852943880668698272019-11-08T17:28:00.001+05:302019-11-10T17:15:57.335+05:30Access modifiers in Java<div dir="ltr" style="text-align: left;" trbidi="on">
Access modifiers in Java define the scope of <b>class</b>, <b>constructor</b>, <b>methods</b> and <b>variable</b>.<br />
<b><br /></b><span style="font-size: large;">
<b>Why access modifiers?</b></span><br />
The whole concept of access modifier is "What you want to expose from class".<br />
<br />
There are total four access modifier <b class="inlineCode">public</b>, <b class="inlineCode">protected</b>, <b class="inlineCode">default</b> and <b class="inlineCode">private</b> in Java.<br />
<br />
<span style="font-size: large;"><b>public</b></span> - As name suggest any class, constructor, method and variable marked as public can be accessed within class, from sub/child-class, within same package or out of package. In other word "Can be accessed globally".<br />
<br />
<span style="font-size: large;"><b>protected</b></span> - Any Inner class, constructor, method and variable marked
as protected can be accessed within class, from sub/child-class created
in <b>same package or different package</b>, via object creation in same package.<br />
<br />
You can not access protected Inner class, constructor, method and variable via object created in different package.<br />
<br />
<span style="font-size: large;"><b>default</b></span> - No access specifier defined for any Inner class,
constructor, method and variable considered as default access level. It
can be accessed within class, from sub/child-class created in same
package only.<br />
<br />
Default class, inner class, constructor, method and variables are not visible out side of package.<br />
<br />
<span style="font-size: large;"><b>private</b></span> - As name suggest any Inner class, constructor, method and variable marked as private can be accessed within <b>same class only</b>.<br />
<br />
<br />
All access modifier's scope is given in following table.<br />
<br />
<table border="1" style="text-align: center; width: 100%;">
<thead style="background: lightgrey;">
<tr>
<th>Access Modifier</th>
<th>same class</th>
<th>same package<br />
via sub-class/object</th>
<th>sub class in<br />
different package</th>
<th>outside<br />
the package</th>
</tr>
</thead>
<tbody>
<tr>
<td>public</td>
<td>Yes</td>
<td>Yes</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td>protected</td>
<td>Yes</td>
<td>Yes</td>
<td>Yes</td>
<td style="background-color: #f53271;">No</td>
</tr>
<tr>
<td>default</td>
<td>Yes</td>
<td>Yes</td>
<td style="background-color: #f53271;">No</td>
<td style="background-color: #f53271;">No</td>
</tr>
<tr>
<td>private</td>
<td>Yes</td>
<td style="background-color: #f53271;">No</td>
<td style="background-color: #f53271;">No</td>
<td style="background-color: #f53271;">No</td>
</tr>
</tbody>
</table>
<br /></div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-1306425083984351582018-09-29T11:52:00.001+05:302018-09-30T12:50:25.276+05:30Spring boot rest api with Mongodb CRUD examples<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://4.bp.blogspot.com/-TevOgPVC2dE/WnILAnucRVI/AAAAAAAAGU4/Y0eg10SP5f4niLZAKex2EeRDvJkGfP7vgCPcBGAYYCw/s1600/spring-boot.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="300" data-original-width="700" src="https://4.bp.blogspot.com/-TevOgPVC2dE/WnILAnucRVI/AAAAAAAAGU4/Y0eg10SP5f4niLZAKex2EeRDvJkGfP7vgCPcBGAYYCw/s1600/spring-boot.png" /></a></div>
In previous articles we have seen <a class="externalLink" href="http://www.javaquery.com/2018/02/creating-first-rest-api-in-spring-boot.html" target="_blank">Creating first rest api in spring-boot</a> and also <a class="externalLink" href="http://www.javaquery.com/2018/02/passing-and-validating-requestparam-in.html" target="_blank">Passing and validating RequestParam in spring-boot rest api</a> now we will take one step further by interacting with database. Also checkout <a href="https://www.javaquery.com/2018/04/interacting-with-mysql-database-using.html" class="externalLink" target="_blank">Spring boot rest api with MySQL CRUD examples</a> or browse all spring tutorials <a class="externalLink" href="http://www.javaquery.com/p/spring-tutorials.html" target="_blank">here</a>.<br />
<br />
<b><span style="font-size: large;">build.gradle</span></b><br />
update your <b class="inlineCode">build.gradle</b>, add following dependencies and refresh the project, gradle will download the required dependencies(jar files).<br />
<pre class="prettyprint">//mongodb dependencies
compile('org.springframework.boot:spring-boot-starter-data-mongodb')
</pre>
<b><span style="font-size: large;">application.properties</span></b><br />
Create new <b>source</b> folder under <b class="inlineCode">src/main/resources</b> if not exist and add new file called <b class="inlineCode">application.properties</b>. Add following lines for database connection.<br />
<pre class="prettyprint">#mongodb
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.database=spring_boot_examples
spring.data.mongodb.username=root
spring.data.mongodb.password=root
</pre>
<br />
<b><span style="font-size: large;">Source code (User.java)</span></b><br />
<b>Note:</b> In current example we are using spring boot 1.5.7.RELEASE which uses validations framework 1.1.0. <b class="inlineCode">@NotEmpty</b>, <b class="inlineCode">@Email</b> are part of package org.hibernate.validator. But spring boot 2.0.0 and above which supports validation framework 2.0 so <b class="inlineCode">@NotEmpty</b>, <b class="inlineCode">@Email</b>, etc... are now part of javax.validation.constraints.
<br />
<pre class="prettyprint">import java.util.Date;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
/**
* @author javaQuery
* @since 2018-09-24
* @github https://github.com/javaquery/spring-boot-examples
*/
@Document(collection = "users")
public class User{
@Id
public String id;
@Field("first_name")
@NotEmpty(message = "first_name can not be empty.")
@Size(max = 100, message = "first_name can not be more than 100 characters.")
private String firstName;
@Field("last_name")
@NotEmpty(message = "last_name can not be empty.")
@Size(max = 100, message = "last_name can not be more than 100 characters.")
private String lastName;
@Field("email")
@NotEmpty(message = "email can not be empty.")
@Size(max = 100, message = "email can not be more than 100 characters.")
private String email;
@Field("password")
@NotEmpty(message = "password can not be empty.")
@Size(max = 100, message = "password can not be more than 100 characters.")
private String password;
@Field("created")
private Long created = (new Date().getTime())/ 1000;
@Field("modified")
private Long modified = (new Date().getTime())/ 1000;
//getter-setter
}
</pre>
<br />
<b><span style="font-size: large;">Abstraction in Spring</span></b><br />
Spring is all about abstraction via <a class="externalLink" href="http://javainterfaces.com/" target="_blank">interfaces</a>. Abstraction allows you to change the implementation without affecting caller method.<br />
<br />
<b><span style="font-size: large;">Repositories</span></b><br />
<div class="blockquote">
The goal of Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores.
</div>
Spring Repository(interface) is abstraction for data access layer.<br />
<br />
For example in your project you are going to use data storage like MySQL(RDBMS), MongoDb (NoSQL), etc... The caller class will interact to data storage using repository(interface) so for caller class it doesn't matter which storage you are using in implementation of repository either MySQL or MongoDb as long as data persist and retrieve back.<br />
<br />
Here we are using <b>MongoRepository</b> for which spring will provide default implementation of MongoDb queries (INSERT, UPDATE, DELETE, SELECT) without writing it yourself.<br />
<br />
<b><span style="font-size: large;">Source code (MongoRepository.java)</span></b><br />
<pre class="prettyprint">import java.util.UUID;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.javaquery.examples.springboot.model.mongodb.User;
/**
* @author javaQuery
* @since 2018-09-24
* @github https://github.com/javaquery/spring-boot-examples
*/
public interface UserMongoDbRepository extends MongoRepository<User, String>{
}
</pre>
Now if you want to save record (User), all you got to do is call <b class="inlineCode">userMongoDbRepository.save(user);</b>. Calling <b>save</b> on <b>UserRepository</b> will generate <b class="inlineCode">INSERT</b> statement and execute it. Similarly you can perform update, select and delete.<br />
<br />
<b><span style="font-size: large;">Source code (Application.java)</span></b><br />
Add <b class="inlineCode">@EnableMongoRepositories</b> in your Application.java.
<br />
<pre class="prettyprint">import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
/**
* @author javaQuery
* @since 2018-01-31
* @github https://github.com/javaquery/spring-boot-examples
*/
@SpringBootApplication
@ComponentScan(basePackages = { "com.javaquery.examples.springboot.rest" })
@EnableMongoRepositories("com.javaquery.examples.springboot.model.mongodb.repositories")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
</pre>
<ul>
<li><b>@EnableMongoRepositories</b> - Location(package) of your code which interact with database (repositories)</li>
</ul>
<hr />
<b><span style="font-size: large;">Services</span></b><br />
Service is abstraction layer for application logic implementation.<br />
<br />
<b><span style="font-size: large;">Source code (UserMongoDbService.java)</span></b><br />
<b>UserMongoDbDTO</b> / <b>UserMongoDbDTO</b> are request objects (JSON Payload). Source code is available under controller section.<br />
<pre class="prettyprint">
import com.javaquery.examples.springboot.rest.dto.UserMongoDbDTO;
import com.javaquery.examples.springboot.rest.dto.UserUpdateDTO;
/**
* @author javaQuery
* @since 2018-09-24
* @github https://github.com/javaquery/spring-boot-examples
*/
public interface UserMongoDbService {
public UserMongoDbDTO addUser(UserMongoDbDTO userDTO);
public UserMongoDbDTO getUser(String id);
public UserMongoDbDTO updateUser(UserUpdateDTO userUpdateDTO, String id);
public void deleteUser(String id);
}
</pre>
<b><span style="font-size: large;">Source code (UserMongoDbServiceImpl.java)</span></b><br />
<pre class="prettyprint">
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.javaquery.examples.springboot.model.mongodb.User;
import com.javaquery.examples.springboot.model.mongodb.repositories.UserMongoDbRepository;
import com.javaquery.examples.springboot.rest.dto.UserMongoDbDTO;
import com.javaquery.examples.springboot.rest.dto.UserUpdateDTO;
import com.javaquery.examples.springboot.rest.exception.EntityNotFoundException;
import com.javaquery.examples.springboot.rest.service.UserMongoDbService;
/**
* @author javaQuery
* @since 2018-09-24
* @github https://github.com/javaquery/spring-boot-examples
*/
@Service
public class UserMongoDbServiceImpl implements UserMongoDbService {
@Autowired
private UserMongoDbRepository userMongoDbRepository;
@Override
public UserMongoDbDTO addUser(UserMongoDbDTO userDTO) {
/**
* We are manually creating {@link User} object however there is mapper
* available to convert to-from {@link UserDTO}.
*/
User user = new User();
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
user.setEmail(userDTO.getEmail());
user.setPassword(userDTO.getPassword());
userMongoDbRepository.save(user);
/* set generated user id to response object */
userDTO.setId(user.getId());
userDTO.setPassword("");
return userDTO;
}
@Override
public UserMongoDbDTO getUser(String id) {
User user = userMongoDbRepository.findOne(id);
if (Objects.isNull(user)) {
/* handle this exception using {@link RestExceptionHandler} */
throw new EntityNotFoundException(User.class, id);
}
return new UserMongoDbDTO().build(user);
}
@Override
public UserMongoDbDTO updateUser(UserUpdateDTO userUpdateDTO, String id) {
User user = userMongoDbRepository.findOne(id);
if (Objects.isNull(user)) {
/* handle this exception using {@link RestExceptionHandler} */
throw new EntityNotFoundException(User.class, id);
}
user.setFirstName(userUpdateDTO.getFirstName());
user.setLastName(userUpdateDTO.getLastName());
userMongoDbRepository.save(user);
return new UserMongoDbDTO().build(user);
}
@Override
public void deleteUser(String id) {
userMongoDbRepository.delete(id);
}
}
</pre>
<hr />
<b><span style="font-size: large;">Controller (REST)</span></b><br />
Controller is the entry point for all REST request.<br />
<br />
<b><span style="font-size: large;">Source code (UserMongoDbDTO.java)</span></b><br />
<pre class="prettyprint">
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.javaquery.examples.springboot.model.mongodb.User;
/**
* Object to interact using rest api.
*
* @author javaQuery
* @since 2018-09-24
* @github https://github.com/javaquery/spring-boot-examples
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class UserMongoDbDTO {
/* used to send database id */
private String id;
@NotEmpty(message = "first_name can not be empty")
@JsonProperty("first_name")
private String firstName;
@NotEmpty(message = "last_name can not be empty")
@JsonProperty("last_name")
private String lastName;
@Email
@JsonProperty("email")
private String email;
@NotEmpty(message = "password can not be empty")
@Size(min = 6, message = "password must be at least 6 character")
@JsonProperty("password")
private String password;
// getter - setter
/**
* We are manually creating {@link UserMongoDbDTO} object however there is
* mapper available to convert to-from {@link User}.
*
* @param user
* @return
*/
public UserMongoDbDTO build(User user) {
this.id = user.getId();
this.firstName = user.getFirstName();
this.lastName = user.getLastName();
this.email = user.getEmail();
return this;
}
}
</pre>
<br />
<b><span style="font-size: large;">Source code (UserUpdateDTO.java)</span></b><br />
<pre class="prettyprint">import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Object to interact using rest api.
* @author javaQuery
* @since 2018-02-18
* @github https://github.com/javaquery/spring-boot-examples
*/
public class UserUpdateDTO {
@NotEmpty(message = "first_name can not be empty")
@JsonProperty("first_name")
private String firstName;
@NotEmpty(message = "last_name can not be empty")
@JsonProperty("last_name")
private String lastName;
// getter - setter
}
</pre>
<br />
<b><span style="font-size: large;">Source code (UserMongoDbController.java)</span></b><br />
Http request <b class="inlineCode">POST</b>, <b class="inlineCode">GET</b>, <b class="inlineCode">PUT</b> and <b class="inlineCode">POST</b> are implemented in controller.
<br />
<pre class="prettyprint">
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.javaquery.examples.springboot.rest.dto.UserMongoDbDTO;
import com.javaquery.examples.springboot.rest.dto.UserUpdateDTO;
import com.javaquery.examples.springboot.rest.response.SuccessResponse;
import com.javaquery.examples.springboot.rest.service.UserMongoDbService;
/**
* @author javaQuery
* @since 2018-09-24
* @github https://github.com/javaquery/spring-boot-examples
*/
@RestController
@RequestMapping("/api/user/mongodb")
public class UserMongoDbController {
@Autowired
private UserMongoDbService userMongoDbService;
@PostMapping
public ResponseEntity<UserMongoDbDTO> addUser(@Valid @RequestBody UserMongoDbDTO userDTO) {
return ResponseEntity.ok(userMongoDbService.addUser(userDTO));
}
@GetMapping
public ResponseEntity<UserMongoDbDTO> getUser(@RequestParam String id) {
return ResponseEntity.ok(userMongoDbService.getUser(id));
}
@PutMapping
public ResponseEntity<UserMongoDbDTO> updateUser(@Valid @RequestBody UserUpdateDTO userUpdateDTO, @RequestParam String id) {
return ResponseEntity.ok(userMongoDbService.updateUser(userUpdateDTO, id));
}
@DeleteMapping
public ResponseEntity<?> deleteUser(@RequestParam String id) {
userMongoDbService.deleteUser(id);
return ResponseEntity.ok(new SuccessResponse("deleted"));
}
}
</pre>
<b>Note:</b> Add updated <a class="externalLink" href="https://github.com/javaquery/spring-boot-examples/blob/master/src/main/java/com/javaquery/examples/springboot/rest/exception/EntityNotFoundException.java" target="_blank">EntityNotFoundException.java</a> and <a class="externalLink" href="https://github.com/javaquery/spring-boot-examples/blob/master/src/main/java/com/javaquery/examples/springboot/rest/exception/RestExceptionHandler.java" target="_blank">RestExceptionHandler.java</a> from github.
<br />
<hr />
<b><span style="font-size: large;">Request/Response</span></b><br />
<table class="request-response">
<thead>
<tr>
<td>cURL POST <a class="externalLink" href="http://localhost:8080/api/user/mongodb" target="_blank">http://localhost:8080/api/user/mongodb</a><br />
-body {"first_name":"vicky","last_name":"thakor","email":"vicky.thakor@javaquery.com","password":"123456"}
</td>
</tr>
</thead>
<tbody>
<tr>
<td><pre style="overflow: scroll;">-code 200
-body {"id":"5bada32eac0eb2127413b580","first_name":"vicky","last_name":"thakor","email":"vicky.thakor@javaquery.com","password":""}</pre>
</td>
</tr>
</tbody>
</table>
<table class="request-response">
<thead>
<tr>
<td>cURL GET <a class="externalLink" href="http://localhost:8080/api/user/mongodb?id=5bada32eac0eb2127413b580" target="_blank">http://localhost:8080/api/user/mongodb?id=5bada32eac0eb2127413b580</a></td>
</tr>
</thead>
<tbody>
<tr>
<td><pre style="overflow: scroll;">-code 200
-body {"id":"5bada32eac0eb2127413b580","first_name":"vicky","last_name":"thakor","email":"vicky.thakor@javaquery.com"}</pre>
</td>
</tr>
</tbody>
</table>
<table class="request-response">
<thead>
<tr>
<td>cURL PUT <a class="externalLink" href="http://localhost:8080/api/user/mongodb?id=5bada32eac0eb2127413b580" target="_blank">http://localhost:8080/api/user/mongodb?id=5bada32eac0eb2127413b580</a><br />
-body {"first_name":"vickey","last_name":"thakor"}</td>
</tr>
</thead>
<tbody>
<tr>
<td><pre style="overflow: scroll;">-code 200
-body {"id":"5bada32eac0eb2127413b580","first_name":"vickey","last_name":"thakor","email":"vicky.thakor@javaquery.com"}</pre>
</td>
</tr>
</tbody>
</table>
<table class="request-response">
<thead>
<tr>
<td>cURL DELETE <a class="externalLink" href="http://localhost:8080/api/user/mongodb?id=5bada32eac0eb2127413b580" target="_blank">http://localhost:8080/api/user/mongodb?id=5bada32eac0eb2127413b580</a></td>
</tr>
</thead>
<tbody>
<tr>
<td><pre>-code 200
-body {"message": "deleted"}</pre>
</td>
</tr>
</tbody>
</table>
<br /></div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-11592834914599060062018-06-03T16:15:00.000+05:302018-06-03T16:15:28.026+05:30How to set value in Text Field of Jasper Report?<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: center;">
<iframe allowfullscreen="" class="youtube-player" frameborder="0" height="350" src="https://www.youtube.com/embed/yx3dWITw28w?wmode=transparent&fs=1&hl=en&modestbranding=1&iv_load_policy=3&showsearch=0&rel=0&theme=light" style="text-align: left;" title="YouTube video player" type="text/html" width="575"></iframe></div><br/>
<b><span style="font-size: large;">Source code (template_jasper_text_field.jrxml)</span></b><br />
<pre class="prettyprint"><?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.1.1.final using JasperReports Library version 6.1.1 -->
<!-- 2018-06-03T15:20:40 -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="template_jasper_text_field" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="67995913-5292-4c36-b77b-bab4e01b985c">
<parameter name="billingAddress" class="java.lang.String"/>
<parameter name="shippingAddress" class="java.lang.String"/>
<queryString>
<![CDATA[]]>
</queryString>
<background>
<band splitType="Stretch"/>
</background>
<title>
<band height="175" splitType="Stretch">
<staticText>
<reportElement x="0" y="0" width="100" height="20" uuid="6d933de8-de74-4b47-b2f9-9f16f8f80a13"/>
<text><![CDATA[Billing Address:]]></text>
</staticText>
<textField>
<reportElement x="0" y="20" width="200" height="100" uuid="353295e2-3e1e-4e8d-93f9-e3f659c95039"/>
<textFieldExpression><![CDATA[$P{billingAddress}]]></textFieldExpression>
</textField>
<staticText>
<reportElement x="320" y="0" width="100" height="20" uuid="3e9df9ea-5f99-4246-9982-f55a5bd7c305"/>
<text><![CDATA[Shipping Address:]]></text>
</staticText>
<textField>
<reportElement x="320" y="20" width="220" height="100" uuid="2c5f72d8-f571-4b00-a1fd-a4bbc500542d"/>
<textFieldExpression><![CDATA[$P{shippingAddress}]]></textFieldExpression>
</textField>
</band>
</title>
<pageHeader>
<band height="35" splitType="Stretch"/>
</pageHeader>
<columnHeader>
<band height="61" splitType="Stretch"/>
</columnHeader>
<detail>
<band height="125" splitType="Stretch"/>
</detail>
<columnFooter>
<band height="45" splitType="Stretch"/>
</columnFooter>
<pageFooter>
<band height="54" splitType="Stretch"/>
</pageFooter>
<summary>
<band height="42" splitType="Stretch"/>
</summary>
</jasperReport>
</pre>
<br />
<b><span style="font-size: large;">Source code (JasperReportTextFieldExample.java)</span></b><br />
<pre class="prettyprint">import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
/**
* @author javaQuery
* @since 2018-05-27
* @github https://github.com/javaquery/Examples
*/
public class JasperReportTextFieldExample {
public static void main(String[] args) {
try {
/* User home directory location */
String userHomeDirectory = System.getProperty("user.home");
/* Output file location */
String outputFile = userHomeDirectory + File.separatorChar + "JasperReportTextFieldExample.pdf";
/* Map to hold Jasper report Parameters */
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("billingAddress", "Google LLC,\n1600 Amphitheatre Parkway Mountain View,\nCA 94043 USA");
parameters.put("shippingAddress", "Google LLC,\n1600 Amphitheatre Parkway Mountain View,\nCA 94043 USA");
/* Using compiled version(.jasper) of Jasper report to generate PDF */
JasperPrint jasperPrint = JasperFillManager.fillReport("resources/com/javaquery/jasper/templates/template_jasper_text_field.jasper", parameters, new JREmptyDataSource());
/* outputStream to create PDF */
OutputStream outputStream = new FileOutputStream(new File(outputFile));
/* Write content to PDF file */
JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
System.out.println("File Generated: " + outputFile);
} catch (JRException ex) {
ex.printStackTrace();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
}
</pre>
</div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-24261205046635804352018-05-19T16:45:00.001+05:302018-05-19T16:50:21.838+05:30Spring internationalization(i18n) example for response and errors<div dir="ltr" style="text-align: left;" trbidi="on">
Nowadays, your application has users from around the world. For ease of your user, you want them to use web application in their local language. You must consider internationalization (i18n) while creating your web application.<br />
<br />
In following example we will learn how you can apply internationalization to your spring application. In my previous articles we learned <a class="externalLink" href="http://www.javaquery.com/2018/02/creating-first-rest-api-in-spring-boot.html" target="_blank">Creating first rest api in spring-boot</a> and you can browse <a class="externalLink" href="https://www.javaquery.com/p/spring-tutorials.html" target="_blank">all spring article</a> for starter.<br />
<br />
<b><span style="font-size: large;">Language specific properties file</span></b><br />
Create properties file under <b class="inlineCode">src/main/resource</b> folder for individual language you want to support in your application. We create package <b>locale</b> under folder and placed all file in it.<br />
<br />
<b>messages_de.properties</b><br />
<pre class="prettyprint">springboot.hello=Hallo
springboot.customerror=benutzerdefinierte Fehlermeldung
</pre>
<b>messages_en.properties</b><br />
<pre class="prettyprint">springboot.hello=Hello
springboot.customerror=custom error message
</pre>
<b>messages_fr.properties</b><br />
<pre class="prettyprint">springboot.hello=Bonjour
springboot.customerror=message d'erreur personnalisé
</pre>
<b>messages_zh.properties</b><br />
For Chinese character you have to convert character / word into Unicode. <a class="externalLink" href="https://www.javaquery.com/2018/05/how-to-convert-chinese-character-or.html" target="_blank">How to convert Chinese character or word to Unicode online?</a><br />
<pre class="prettyprint">springboot.hello=\u4f60\u597d
springboot.customerror=\u81ea\u5b9a\u4e49\u9519\u8bef\u6d88\u606f
</pre>
<br />
<b><span style="font-size: large;">Source code (ApplicationConfig.java)</span></b><br />
Load your language properties file in spring context using <b class="inlineCode">ReloadableResourceBundleMessageSource</b>.
<br />
<pre class="prettyprint">import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* @author javaQuery
* @since 2018-02-18
* @github https://github.com/javaquery/spring-boot-examples
*/
@Configuration
public class ApplicationConfig extends WebMvcConfigurerAdapter{
@Bean
public ReloadableResourceBundleMessageSource messageSource(){
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:locale/messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
/**
* Internationalization for parameter and payload validation messages.
* @return
*/
@Bean
public LocalValidatorFactoryBean validator() {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(messageSource());
return bean;
}
@Override
public Validator getValidator() {
return validator();
}
}
</pre>
<br />
<b><span style="font-size: large;">Source code (Application.java)</span></b><br />
Add <b>ApplicationConfig.java</b> file package <b class="inlineCode">com.javaquery.examples.springboot.main.config</b> in <b>Application.java</b> for component scan.<br />
<pre class="prettyprint">import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
/**
* @author javaQuery
* @since 2018-01-31
* @github https://github.com/javaquery/spring-boot-examples
*
* @change message internationalization (locale)
*/
@SpringBootApplication
@ComponentScan(basePackages = { "com.javaquery.examples.springboot.rest", "com.javaquery.examples.springboot.main.config"})
@EntityScan("com.javaquery.examples.springboot.model")
@EnableJpaRepositories("com.javaquery.examples.springboot.model.repositories")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
</pre>
<br />
<b><span style="font-size: large;">Source code (LocaleController.java)
</span></b><br />
<pre class="prettyprint">import java.util.Locale;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Springboot internationalization example
* @author javaQuery
* @since 2018-04-06
*/
@RestController
@RequestMapping("/api")
@Validated
public class LocaleController {
@Autowired
private MessageSource messageSource;
/**
* Response internationalization.
* @param name
* @param locale
* @return
*/
@GetMapping("/locale")
public ResponseEntity<?> sayHello(@RequestParam("name") String name, Locale locale){
String localeHello = messageSource.getMessage("springboot.hello", null, locale);
return ResponseEntity.ok(localeHello + " " + name);
}
/**
* Validation parameter internationalization.
* @param firstname
* @param lastname
* @param notEmptyParam
* @param locale
* @return
*/
@GetMapping("/locale/param")
public ResponseEntity<?> parameterValidation(@Size(min = 1, max = 5, message = "firstname {javax.validation.constraints.Size.message}") @RequestParam("firstname") String firstname,
@NotEmpty(message = "lastname {org.hibernate.validator.constraints.NotEmpty.message}") @RequestParam("lastname") String lastname,
@NotEmpty(message = "{springboot.customerror}") String notEmptyParam, Locale locale){
String localeHello = messageSource.getMessage("springboot.hello", null, locale);
return ResponseEntity.ok(localeHello + " " + firstname + " " + lastname);
}
}
</pre>
We used properties file key <b class="inlineCode">springboot.hello</b> to send language specific response of "Hello".<br />
<br />
<b><span style="font-size: large;">Internationalization for error messages</span></b><br />
<b>parameterValidation</b> method demonstrate use of internationalization code for validation.<br />
- You can create your own custom code like <b class="inlineCode">{springboot.customerror}</b>.<br />
- Use inbuilt codes. You find out internationalization code from source of annotation.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-9L-2q_1_z6s/Wv_-veOkNYI/AAAAAAAAGXY/mWZa8s2gkSwgEWwq-0zMKe912XJqZIdzQCLcBGAs/s1600/Size%2Bannotation%2Bsource%2Bcode.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="192" data-original-width="624" src="https://2.bp.blogspot.com/-9L-2q_1_z6s/Wv_-veOkNYI/AAAAAAAAGXY/mWZa8s2gkSwgEWwq-0zMKe912XJqZIdzQCLcBGAs/s1600/Size%2Bannotation%2Bsource%2Bcode.png" /></a></div>
<br />
<b><span style="font-size: large;">Enable Internationalization</span></b><br />
To enable internationalization for http request send header <b class="inlineCode">accept-language</b> in your request.
<br />
<hr />
<b><span style="font-size: large;">Request/Response</span></b><br />
<table class="request-response">
<thead>
<tr>
<td>cURL POST <a class="externalLink" href="localhost:8080/api/locale?name=vicky" target="_blank">localhost:8080/api/locale?name=vicky</a><br />
-H 'accept-language: fr'
</td>
</tr>
</thead>
<tbody>
<tr>
<td>-code 200<br />
-body Bonjour vicky
</td>
</tr>
</tbody>
</table>
<table class="request-response">
<thead>
<tr>
<td>cURL POST <a class="externalLink" href="localhost:8080/api/locale/param?firstname=VickyV&lastname=Thakor" target="_blank">localhost:8080/api/locale/param?firstname=VickyV&lastname=Thakor</a><br />
-H 'accept-language: de'
</td>
</tr>
</thead>
<tbody>
<tr>
<td>-code 400<br />
-body {"errors":["firstname muss zwischen 1 und 5 liegen","benutzerdefinierte Fehlermeldung"]}
</td>
</tr>
</tbody>
</table>
</div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-43743543412176993702018-05-19T15:41:00.000+05:302018-05-19T15:41:23.666+05:30How to convert Chinese character or word to Unicode online?<div dir="ltr" style="text-align: left;" trbidi="on">
<b><span style="font-size: large;">Step 1: Use Google Translator</span></b><br />
Use <a href="https://translate.google.com/?utm_source=www.javaquery.com" target="_blank" class="externalLink">https://translate.google.com</a> to convert your character or word to Chinese. And copy the Chinese character from Google translate.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://3.bp.blogspot.com/-AtLaGE8s2GY/Wv_1Rqza_9I/AAAAAAAAGXA/B2Rd0VfxEHoAFp8GSw6XZVPLvlfAQqsmQCLcBGAs/s1600/Use%2BGoogle%2BTranslate%2Bto%2BConvert%2BChinese%2BCharacter.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="245" data-original-width="738" src="https://3.bp.blogspot.com/-AtLaGE8s2GY/Wv_1Rqza_9I/AAAAAAAAGXA/B2Rd0VfxEHoAFp8GSw6XZVPLvlfAQqsmQCLcBGAs/s1600/Use%2BGoogle%2BTranslate%2Bto%2BConvert%2BChinese%2BCharacter.png" /></a></div>
<br />
<b><span style="font-size: large;">Step 2: Use any online website for native2ascii conversion.</span></b><br />
We will <a href="https://native2ascii.net/?utm_source=www.javaquery.com" target="_blank" class="externalLink">https://native2ascii.net</a> for conversion. Copy the generated Unicode character on right hand side.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://4.bp.blogspot.com/-wlJti5bndUU/Wv_3rMhlzUI/AAAAAAAAGXM/pR0D7IhMygsMN79MZJnsrArrJmhQTsj4ACLcBGAs/s1600/Interactive%2Bnative2ascii.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="257" data-original-width="1162" height="141" src="https://4.bp.blogspot.com/-wlJti5bndUU/Wv_3rMhlzUI/AAAAAAAAGXM/pR0D7IhMygsMN79MZJnsrArrJmhQTsj4ACLcBGAs/s640/Interactive%2Bnative2ascii.png" width="640" /></a></div>
<br /></div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-41705365665072069862018-04-05T08:36:00.001+05:302018-09-29T11:54:32.026+05:30Spring boot rest api with MySQL CRUD examples<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://4.bp.blogspot.com/-TevOgPVC2dE/WnILAnucRVI/AAAAAAAAGU4/Y0eg10SP5f4niLZAKex2EeRDvJkGfP7vgCPcBGAYYCw/s1600/spring-boot.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="300" data-original-width="700" src="https://4.bp.blogspot.com/-TevOgPVC2dE/WnILAnucRVI/AAAAAAAAGU4/Y0eg10SP5f4niLZAKex2EeRDvJkGfP7vgCPcBGAYYCw/s1600/spring-boot.png" /></a></div>
<br />
In previous articles we have seen <a class="externalLink" href="http://www.javaquery.com/2018/02/creating-first-rest-api-in-spring-boot.html" target="_blank">Creating first rest api in spring-boot</a> and also <a class="externalLink" href="http://www.javaquery.com/2018/02/passing-and-validating-requestparam-in.html" target="_blank">Passing and validating RequestParam in spring-boot rest api</a> now we will take one step further by interacting with database. Also checkout <a href="https://www.javaquery.com/2018/09/spring-boot-rest-api-with-mongodb-crud.html" class="externalLink" target="_blank">Spring boot rest api with Mongodb CRUD examples</a> or browse all spring tutorials <a class="externalLink" href="http://www.javaquery.com/p/spring-tutorials.html" target="_blank">here</a>.<br />
<br />
<b><span style="font-size: large;">Project structure</span></b><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://4.bp.blogspot.com/-7M8MPiDLQZ4/WomRW0f7CrI/AAAAAAAAGV0/Oh8n7T1P_LI-KQkkbR2xL3gtE8QLYHZ3QCLcBGAs/s1600/Interacting%2Bwith%2BMySQL%2Bdatabase%2Busing%2Bspring-boot%2Brest%2Bapi.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="512" data-original-width="385" src="https://4.bp.blogspot.com/-7M8MPiDLQZ4/WomRW0f7CrI/AAAAAAAAGV0/Oh8n7T1P_LI-KQkkbR2xL3gtE8QLYHZ3QCLcBGAs/s1600/Interacting%2Bwith%2BMySQL%2Bdatabase%2Busing%2Bspring-boot%2Brest%2Bapi.png" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<b><span style="font-size: large;">build.gradle</span></b><br />
update your <b class="inlineCode">build.gradle</b>, add following dependencies and refresh the project, gradle will download the required dependencies(jar files).<br />
<pre class="prettyprint">// database dependencies
compile('org.springframework.boot:spring-boot-starter-data-jpa')
runtime('mysql:mysql-connector-java')
</pre>
<b><span style="font-size: large;">application.properties</span></b><br />
Create new <b>source</b> folder under <b class="inlineCode">src/main/resources</b> if not exist and add new file called <b class="inlineCode">application.properties</b>. Add following lines for database connection.<br />
<pre class="prettyprint">#datasource configurations
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot_examples
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.show-sql=true
#spring.jpa.properties.hibernate.format_sql=true
</pre>
Now create table <b class="inlineCode">users</b> in database. Create table sql script is available on <a class="externalLink" href="https://github.com/javaquery/spring-boot-examples/blob/master/src/main/resources/sql/users.sql" target="_blank">github</a>.<br />
<br />
<b><span style="font-size: large;">Source code (User.java)</span></b><br />
We used <a class="externalLink" href="http://www.javainterfaces.com/databaseentity.php" target="_blank">DatabaseEntity</a> and <a class="externalLink" href="http://www.javainterfaces.com/modifiableentity.php" target="_blank">ModifiableEntity</a> interfaces from <a class="externalLink" href="http://www.javainterfaces.com/" target="_blank">Java Interfaces</a>. Also we used <a class="externalLink" href="http://www.javaquery.com/2018/02/constraints-validation-for-user-inputs.html" target="_blank">Java Constraint Validation</a> on each column.<br />
<b>Note:</b> In current example we are using spring boot 1.5.7.RELEASE which uses validations framework 1.1.0. <b class="inlineCode">@NotEmpty</b>, <b class="inlineCode">@Email</b> are part of package org.hibernate.validator. But spring boot 2.0.0 and above which supports validation framework 2.0 so <b class="inlineCode">@NotEmpty</b>, <b class="inlineCode">@Email</b>, etc... are now part of javax.validation.constraints.
<br />
<pre class="prettyprint">import java.util.Date;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Size;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.validator.constraints.NotEmpty;
/**
* @author javaQuery
* @since 2018-02-18
* @github https://github.com/javaquery/spring-boot-examples
*/
@Entity
@Table(name = "users")
public class User implements DatabaseEntity, ModifiableEntity{
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(name = "id", columnDefinition = "BINARY(16)")
private UUID id;
@Column(name = "first_name")
@NotEmpty(message = "first_name can not be empty.")
@Size(max = 100, message = "first_name can not be more than 100 characters.")
private String firstName;
@Column(name = "last_name")
@NotEmpty(message = "last_name can not be empty.")
@Size(max = 100, message = "last_name can not be more than 100 characters.")
private String lastName;
@Column(name = "email")
@NotEmpty(message = "email can not be empty.")
@Size(max = 100, message = "email can not be more than 100 characters.")
private String email;
@Column(name = "password")
@NotEmpty(message = "password can not be empty.")
@Size(max = 100, message = "password can not be more than 100 characters.")
private String password;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created")
private Date created = new Date();
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "modified")
private Date modified = new Date();
//getter-setter
}
</pre>
<br />
<b><span style="font-size: large;">Abstraction in Spring</span></b><br />
Spring is all about abstraction via <a class="externalLink" href="http://javainterfaces.com/" target="_blank">interfaces</a>. Abstraction allows you to change the implementation without affecting caller method.<br />
<br />
<b><span style="font-size: large;">Repositories</span></b><br />
<div class="blockquote">
The goal of Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores.
</div>
Spring Repository(interface) is abstraction for data access layer.<br />
<br />
For example in your project you are going to use data storage like MySQL(RDBMS), MongoDb (NoSQL), etc... The caller class will interact to data storage using repository(interface) so for caller class it doesn't matter which storage you are using in implementation of repository either MySQL or MongoDb as long as data persist and retrieve back.<br />
<br />
Here we are using <b>JpaRepository</b> for which spring will provide default implementation of basic SQL queries (INSERT, UPDATE, DELETE, SELECT) without writing it yourself.<br />
<br />
<b><span style="font-size: large;">Source code (UserRepository.java)</span></b><br />
<pre class="prettyprint">import java.util.UUID;
import org.springframework.data.jpa.repository.JpaRepository;
import com.javaquery.examples.springboot.model.User;
/**
* @author javaQuery
* @since 2018-02-18
*/
public interface UserRepository extends JpaRepository<User, UUID>{
}
</pre>
Now if you want to save record (User), all you got to do is call <b class="inlineCode">userRepository.save(user);</b>. Calling <b>save</b> on <b>UserRepository</b> will generate <b class="inlineCode">INSERT</b> statement and execute it. Similarly you can perform update, select and delete.<br />
<br />
<b><span style="font-size: large;">Source code (Application.java)</span></b><br />
Add <b class="inlineCode">@EntityScan</b> and <b class="inlineCode">EnableJpaRepositories</b> in your Application.java.
<br />
<pre class="prettyprint">import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
/**
* @author javaQuery
* @since 2018-01-31
* @github https://github.com/javaquery/spring-boot-examples
*/
@SpringBootApplication
@ComponentScan(basePackages = { "com.javaquery.examples.springboot.rest" })
@EntityScan("com.javaquery.examples.springboot.model")
@EnableJpaRepositories("com.javaquery.examples.springboot.model.repositories")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
</pre>
<ul>
<li><b>@EntityScan</b> - Location(package) of your database entities</li>
<li><b>@EnableJpaRepositories</b> - Location(package) of your code which interact with database (repositories)</li>
</ul>
<hr />
<b><span style="font-size: large;">Services</span></b><br />
Service is abstraction layer for application logic implementation.<br />
<br />
<b><span style="font-size: large;">Source code (UserService.java)</span></b><br />
<b>UserDTO</b> / <b>UserUpdateDTO</b> are request objects (JSON Payload). Source code is available under controller section.<br />
<pre class="prettyprint">import java.util.UUID;
import com.javaquery.examples.springboot.rest.dto.UserDTO;
import com.javaquery.examples.springboot.rest.dto.UserUpdateDTO;
/**
* @author javaQuery
* @since 2018-02-18
* @github https://github.com/javaquery/spring-boot-examples
*/
public interface UserService {
public UserDTO addUser(UserDTO userDTO);
public UserDTO getUser(UUID id);
public UserDTO updateUser(UserUpdateDTO userUpdateDTO, UUID id);
public void deleteUser(UUID id);
}
</pre>
<b><span style="font-size: large;">Source code (UserServiceImpl.java)</span></b><br />
<pre class="prettyprint">import java.util.Date;
import java.util.Objects;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.javaquery.examples.springboot.model.User;
import com.javaquery.examples.springboot.model.repositories.UserRepository;
import com.javaquery.examples.springboot.rest.dto.UserDTO;
import com.javaquery.examples.springboot.rest.dto.UserUpdateDTO;
import com.javaquery.examples.springboot.rest.exception.EntityNotFoundException;
import com.javaquery.examples.springboot.rest.service.UserService;
/**
* @author javaQuery
* @since 2018-02-18
* @github https://github.com/javaquery/spring-boot-examples
*/
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserRepository userRepository;
@Override
public UserDTO addUser(UserDTO userDTO) {
Date now = new Date();
/**
* We are manually creating {@link User} object however there is mapper available to convert to-from {@link UserDTO}.
*/
User user = new User();
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
user.setEmail(userDTO.getEmail());
user.setPassword(userDTO.getPassword());
user.setCreated(now);
user.setModified(now);
userRepository.save(user);
/* set generated user id to response object */
userDTO.setId(user.getId());
userDTO.setPassword("");
return userDTO;
}
@Override
public UserDTO getUser(UUID id) {
User user = userRepository.getOne(id);
if(Objects.isNull(user)){
/* handle this exception using {@link RestExceptionHandler} */
throw new EntityNotFoundException(User.class, id);
}
return new UserDTO().build(user);
}
@Override
public UserDTO updateUser(UserUpdateDTO userUpdateDTO, UUID id) {
User user = userRepository.getOne(id);
if(Objects.isNull(user)){
/* handle this exception using {@link RestExceptionHandler} */
throw new EntityNotFoundException(User.class, id);
}
user.setFirstName(userUpdateDTO.getFirstName());
user.setLastName(userUpdateDTO.getLastName());
userRepository.save(user);
return new UserDTO().build(user);
}
@Override
public void deleteUser(UUID id) {
userRepository.delete(id);
}
}
</pre>
<hr />
<b><span style="font-size: large;">Controller (REST)</span></b><br />
Controller is the entry point for all REST request.<br />
<br />
<b><span style="font-size: large;">Source code (UserDTO.java)</span></b><br />
<pre class="prettyprint">import java.util.UUID;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.javaquery.examples.springboot.model.User;
/**
* Object to interact using rest api.
* @author javaQuery
* @since 2018-02-18
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class UserDTO {
/* used to send database id */
private UUID id;
@NotEmpty(message = "first_name can not be empty")
@JsonProperty("first_name")
private String firstName;
@NotEmpty(message = "last_name can not be empty")
@JsonProperty("last_name")
private String lastName;
@Email
@JsonProperty("email")
private String email;
@NotEmpty(message = "password can not be empty")
@Size(min = 6, message = "password must be at least 6 character")
@JsonProperty("password")
private String password;
// getter - setter
/**
* We are manually creating {@link UserDTO} object however there is mapper available
* to convert to-from {@link User}.
* @param user
* @return
*/
public UserDTO build(User user){
this.id = user.getId();
this.firstName = user.getFirstName();
this.lastName = user.getLastName();
this.email = user.getEmail();
return this;
}
}
</pre>
<br />
<b><span style="font-size: large;">Source code (UserUpdateDTO.java)</span></b><br />
<pre class="prettyprint">import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Object to interact using rest api.
* @author javaQuery
* @since 2018-02-18
*/
public class UserUpdateDTO {
@NotEmpty(message = "first_name can not be empty")
@JsonProperty("first_name")
private String firstName;
@NotEmpty(message = "last_name can not be empty")
@JsonProperty("last_name")
private String lastName;
// getter - setter
}
</pre>
<br />
<b><span style="font-size: large;">Source code (UserController.java)</span></b><br />
Http request <b class="inlineCode">POST</b>, <b class="inlineCode">GET</b>, <b class="inlineCode">PUT</b> and <b class="inlineCode">POST</b> are implemented in controller.
<br />
<pre class="prettyprint">import java.util.UUID;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.javaquery.examples.springboot.rest.dto.UserDTO;
import com.javaquery.examples.springboot.rest.dto.UserUpdateDTO;
import com.javaquery.examples.springboot.rest.response.SuccessResponse;
import com.javaquery.examples.springboot.rest.service.UserService;
/**
* @author javaQuery
* @since 2018-02-18
*/
@RestController
@RequestMapping("/api/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public ResponseEntity<UserDTO> addUser(@Valid @RequestBody UserDTO userDTO){
return ResponseEntity.ok(userService.addUser(userDTO));
}
@GetMapping
public ResponseEntity<UserDTO> getUser(@RequestParam UUID id){
return ResponseEntity.ok(userService.getUser(id));
}
@PutMapping
public ResponseEntity<UserDTO> updateUser(@Valid @RequestBody UserUpdateDTO userUpdateDTO, @RequestParam UUID id){
return ResponseEntity.ok(userService.updateUser(userUpdateDTO, id));
}
@DeleteMapping
public ResponseEntity<?> deleteUser(@RequestParam UUID id){
userService.deleteUser(id);
return ResponseEntity.ok(new SuccessResponse("deleted"));
}
}
</pre>
<br />
<b>Note:</b> Add updated <a class="externalLink" href="https://github.com/javaquery/spring-boot-examples/blob/master/src/main/java/com/javaquery/examples/springboot/rest/exception/EntityNotFoundException.java" target="_blank">EntityNotFoundException.java</a> and <a class="externalLink" href="https://github.com/javaquery/spring-boot-examples/blob/master/src/main/java/com/javaquery/examples/springboot/rest/exception/RestExceptionHandler.java" target="_blank">RestExceptionHandler.java</a> from github.
<br />
<hr />
<b><span style="font-size: large;">Request/Response</span></b><br />
<table class="request-response">
<thead>
<tr>
<td>cURL POST <a class="externalLink" href="http://localhost:8080/api/user" target="_blank">http://localhost:8080/api/user</a><br />
-body {"first_name":"vicky","last_name":"thakor","email":"vicky.thakor@javaquery.com","password":"123456"}
</td>
</tr>
</thead>
<tbody>
<tr>
<td><pre style="overflow: scroll;">-code 200
-body {"id":"95572033-9cf1-421a-94a7-dc4cdf7e9c71","first_name":"vicky","last_name":"thakor","email":"vicky.thakor@javaquery.com","password":""}</pre>
</td>
</tr>
</tbody>
</table>
<table class="request-response">
<thead>
<tr>
<td>cURL GET <a class="externalLink" href="http://localhost:8080/api/user?id=95572033-9cf1-421a-94a7-dc4cdf7e9c71" target="_blank">http://localhost:8080/api/user?id=95572033-9cf1-421a-94a7-dc4cdf7e9c71</a></td>
</tr>
</thead>
<tbody>
<tr>
<td><pre style="overflow: scroll;">-code 200
-body {"id":"95572033-9cf1-421a-94a7-dc4cdf7e9c71","first_name":"vicky","last_name":"thakor","email":"vicky.thakor@javaquery.com"}</pre>
</td>
</tr>
</tbody>
</table>
<table class="request-response">
<thead>
<tr>
<td>cURL PUT <a class="externalLink" href="http://localhost:8080/api/user?id=95572033-9cf1-421a-94a7-dc4cdf7e9c71" target="_blank">http://localhost:8080/api/user?id=95572033-9cf1-421a-94a7-dc4cdf7e9c71</a><br />
-body {"first_name":"chirag","last_name":"thakor"}</td>
</tr>
</thead>
<tbody>
<tr>
<td><pre style="overflow: scroll;">-code 200
-body {"id":"95572033-9cf1-421a-94a7-dc4cdf7e9c71","first_name":"chirag","last_name":"thakor","email":"vicky.thakor@javaquery.com"}</pre>
</td>
</tr>
</tbody>
</table>
<table class="request-response">
<thead>
<tr>
<td>cURL DELETE <a class="externalLink" href="http://localhost:8080/api/user?id=95572033-9cf1-421a-94a7-dc4cdf7e9c71" target="_blank">http://localhost:8080/api/user?id=95572033-9cf1-421a-94a7-dc4cdf7e9c71</a></td>
</tr>
</thead>
<tbody>
<tr>
<td><pre>-code 200
-body {"message": "deleted"}</pre>
</td>
</tr>
</tbody>
</table>
<br /></div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-64351795811763825002018-03-21T22:55:00.000+05:302018-03-21T22:55:07.341+05:30What is runtime polymorphism in Java?<div dir="ltr" style="text-align: left;" trbidi="on">
One way you can achieve Runtime polymorphism in java is by Method Overiding. Lets check the code followed by explanation.<br />
<br />
<b><span style="font-size: large;">Source code (Animal.java)</span></b><br />
<pre class="prettyprint">/**
* @author javaQuery
* @date 7th November, 2017
* @Github: https://github.com/javaquery/Examples
*/
public class Animal {
public void run(){
System.out.println("Animal is running...");
}
}
</pre>
<b><span style="font-size: large;">Source code (Dog.java)</span></b><br />
<pre class="prettyprint">/**
* @author javaQuery
* @date 7th November, 2017
* @Github: https://github.com/javaquery/Examples
*/
public class Dog extends Animal{
@Override
public void run() {
System.out.println("Dog is running...");
}
}
</pre>
<b><span style="font-size: large;">Source code (Cat.java)</span></b><br />
<pre class="prettyprint">/**
* @author javaQuery
* @date 7th November, 2017
* @Github: https://github.com/javaquery/Examples
*/
public class Cat extends Animal{
@Override
public void run() {
System.out.println("Cat is running...");
}
}
</pre>
<b><span style="font-size: large;">Source code (Horse.java)</span></b><br />
<pre class="prettyprint">/**
* @author javaQuery
* @date 7th November, 2017
* @Github: https://github.com/javaquery/Examples
*/
public class Horse extends Animal{
}
</pre>
<b><span style="font-size: large;">Source code (RuntimePolymorphismExample.java)</span></b><br />
<pre class="prettyprint">/**
* Example demonstrate Runtime Polymorphism.
*
* @author javaQuery
* @date 7th November, 2017
* @Github: https://github.com/javaquery/Examples
*/
public class RuntimePolymorphismExample {
public static void main(String[] args) {
// super-class
Animal animal = new Animal();
animal.run();
/***********************************************/
/* sub-class `Dog` */
/***********************************************/
Dog dog = new Dog();
dog.run();
animal = dog;
/**
* animal.run()
* It will call referenced object's `run()` method.
* In this case, object of `Dog` class is referred.
*/
animal.run(); // runtime polymorphism
/***********************************************/
/* sub-class `Cat` */
/***********************************************/
animal = new Cat();
/**
* animal.run()
* It will call referenced object's `run()` method.
* In this case, object of `Cat` class is referred.
*/
animal.run(); // runtime polymorphism
/***********************************************/
/* sub-class `Horse` */
/***********************************************/
animal = new Horse();
/**
* animal.run()
* It will call referenced object's `run()` method.
* However in this case, object of `Horse` doesn't contain implementation of `run()` so method
* from the super-class `Animal#run` will be called.
*/
animal.run(); // runtime polymorphism
}
}
</pre>
<b><span style="font-size: large;">Output</span></b><br />
<pre class="prettyprint">Animal is running...
Dog is running...
Dog is running...
Cat is running...
Animal is running...
</pre>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://3.bp.blogspot.com/-67tZKiT73no/WrKUVu6bhlI/AAAAAAAAGWU/5Ro02wtZ1JkPHBVrV6JEq1xw50nYJwUuwCLcBGAs/s1600/Run%2BTime%2BPolymorphism%2Bin%2BJava.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Run Time Polymorphism in Java" border="0" data-original-height="431" data-original-width="667" src="https://3.bp.blogspot.com/-67tZKiT73no/WrKUVu6bhlI/AAAAAAAAGWU/5Ro02wtZ1JkPHBVrV6JEq1xw50nYJwUuwCLcBGAs/s1600/Run%2BTime%2BPolymorphism%2Bin%2BJava.png" title="Run Time Polymorphism in Java" /></a></div>
<br /></div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-49463666047757294432018-02-24T16:18:00.000+05:302018-04-04T08:32:04.677+05:30Constraints validation for user inputs (javax.validation.constraints)<div dir="ltr" style="text-align: left;" trbidi="on">
User input validation is common part of any application. JBoss developers made it easy to validate inputs using Java Bean Validation framework.<br />
<br />
<b><span style="font-size: large;">Bean Validation 2.0</span></b> (<a class="externalLink" href="http://beanvalidation.org/" target="_blank">http://beanvalidation.org</a>, <a class="externalLink" href="https://www.jcp.org/en/jsr/detail?id=380" target="_blank">JSR 380</a>)<br />
We will be using Bean Validation framework 2.0 for the example. Its certified implementation is <a class="externalLink" href="http://hibernate.org/validator/" target="_blank">Hibernate Validator</a> 6.0.1.Final or above. Framework 2.0 require Java 8 or higher version.<br />
<br />
<b><span style="font-size: large;">Source code (User.java)</span></b><br />
<pre class="prettyprint">import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
/**
* @author javaQuery
* @since 2018-02-24
* @github: https://github.com/javaquery/Examples
*/
public class User {
@NotEmpty(message = "firstName can not be empty")
@Size(min = 2, max = 20, message = "firstName length must be between 2 and 20")
private String firstName;
@NotEmpty(message = "lastName can not be empty")
@Size(min = 2, max = 20, message = "lastName length must be between 2 and 20")
private String lastName;
@NotEmpty(message = "nickNames can not be empty")
private List<@Size(min = 2, message = "nickName length must be greater than 2") String> nickNames;
@Email
private String email;
@NotEmpty(message = "password can not be empty")
@Size(min = 6, message = "password length must be at least 6 character")
private String password;
// getter-setter
}
</pre>
<ul style="text-align: left;">
<li><b>@NotEmpty</b> - We are using it to check string can not be empty. Can be used with collection, map or array.</li>
<li><b>@Size</b> - We are using it to check the length of string. Can be used with collection, map or array.</li>
<li><b>@Email</b> - The string has to be a well-formed email address.</li>
</ul>
<div>
There are other annotations like <b>@NotNull</b>, <b>@Min</b>, <b>@Max</b>, <b>@Past</b>, <b>@Future</b>, <b>@PastOrPresent</b>, <b>@FutureOrPresent</b>, etc... Complete list of annotations is available on <a class="externalLink" href="http://beanvalidation.org/2.0/spec/#builtinconstraints" target="_blank">Bean Validation specification</a>.</div>
<br />
<b><span style="font-size: large;">Source code (ValidatorFactoryExample.java)
</span></b><br />
<pre class="prettyprint">import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
/**
* @author javaQuery
* @since 2018-02-24
* @github: https://github.com/javaquery/Examples
*/
public class ValidatorFactoryExample {
public static void main(String[] args) {
User user = new User();
user.setFirstName("Vicky");
user.setEmail("not-an-email");
user.setNickNames(Arrays.asList("vicks", "v"));
user.setPassword("1234567");
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
/* validate object and get constraints failed */
Set<ConstraintViolation<User>> violations = validator.validate(user);
for (ConstraintViolation<User> violation : violations) {
System.err.println(violation.getMessage());
}
}
}
</pre>
<br />
<b><span style="font-size: large;">Output</span></b><br />
<pre class="prettyprint">nick name lenght must be greater than 2
lastName can not be empty
must be a well-formed email address
</pre>
<br />
<i>Other frameworks like <b>Spring</b> triggers validation using annotation so you don't have to validate bean on your own like we did using <b>ValidatorFactory</b>.</i><br />
<br />
<b>Similar</b><br />
<a href="https://www.javaquery.com/2018/02/passing-and-validating-requestparam-in.html" target="_blank" class="externalLink">Passing and validating RequestParam in spring-boot rest api</a></div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-35960368870076743802018-02-13T09:58:00.001+05:302018-04-04T08:30:09.124+05:30Passing and validating RequestParam in spring-boot rest api<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://4.bp.blogspot.com/-TevOgPVC2dE/WnILAnucRVI/AAAAAAAAGU4/Y0eg10SP5f4niLZAKex2EeRDvJkGfP7vgCPcBGAYYCw/s1600/spring-boot.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="300" data-original-width="700" src="https://4.bp.blogspot.com/-TevOgPVC2dE/WnILAnucRVI/AAAAAAAAGU4/Y0eg10SP5f4niLZAKex2EeRDvJkGfP7vgCPcBGAYYCw/s1600/spring-boot.png" /></a></div>
In my previous article <a class="externalLink" href="http://www.javaquery.com/2018/02/creating-first-rest-api-in-spring-boot.html" target="_blank">Creating first rest api in spring-boot</a> we learned how you can create rest api. Now lets learn how you can pass <b>parameters</b> to api and validate it. In this example I'm going to use code from my previous article or you can head to <a class="externalLink" href="http://www.javaquery.com/p/spring-tutorials.html" target="_blank">Spring Tutorials</a> page.<br />
<br />
<b><span style="font-size: large;">@RequestParam</span></b><br />
<div class="blockquote">
Annotation which indicates that a method parameter should be bound to a web request parameter.
</div>
<br />
<b><span style="font-size: large;">Source code (HelloWorldController.java)</span></b><br />
<pre class="prettyprint">import javax.validation.constraints.Size;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author javaQuery
* @since 2018-01-31
* @github https://github.com/javaquery/spring-boot-examples
*/
@RestController
@RequestMapping("/api")
@Validated
public class HelloWorldController {
/**
* This will send Hello {name-from-parameter} in response with HTTP status code 200.
* @since 2018-02-01
* @param firstname
* @param lastname
* @return
*/
@GetMapping("/hello")
public ResponseEntity<?> sayHello(
@RequestParam @Size(min= 1, max = 5, message = "firstname length must be between 1 and 5") String firstname,
@RequestParam String middlename,
@RequestParam(required = false) String lastname){
/* check lastname value */
lastname = lastname != null ? lastname : "{lastname-is-optional}";
return ResponseEntity.ok("Hello " + firstname + " " + middlename + " " + lastname);
}
}
</pre>
<b><span style="font-size: large;">Request parameter syntax</span></b><br />
Using <b class="inlineCode">@RequestParam</b> spring rest api accept parameters from the request. You can also use various annotation from package <b class="inlineCode">javax.validation.constraints</b> with <b>@RequestParam</b>.
<br />
<div class="blockquote">
@RequestParam <data_type> <variable_name>;</div>
<br />
Lets quickly understand annotations used in <b>HelloWorldController.java</b>. As we already discussed few annotations in <a class="externalLink" href="http://www.javaquery.com/2018/02/creating-first-rest-api-in-spring-boot.html" target="_blank">Creating first rest api in spring-boot</a> so we will talk about new annotations only.<br />
<br />
<ul style="text-align: left;">
<li><b>@Validated</b> - To perform validation on each method of controller if any.</li>
<li><b>@RequestParam</b> - To accept web request parameter in variable. (<b>Note</b>: All variable annotated with <b>@RequestParam</b> are compulsory/mandatory for request, until you set <b>required = false</b> <b class="inlineCode">@RequestParam(required = false)</b> for that parameter)</li>
</ul>
<b>Request parameter variations</b><br />
<pre class="prettyprint">@RequestParam @Size(min= 1, max = 5 , message = "firstname length must be between 1 and 5") String firstname
</pre>
- <b class="inlineCode">@Size</b> of package <b class="inlineCode">javax.validation.constraints</b> is used to validate length of parameter in request and will throw <b class="inlineCode">ConstraintViolationException</b> if data is not valid. You can read more about <a href="https://www.javaquery.com/2018/02/constraints-validation-for-user-inputs.html" target="_blank" class="externalLink">Constraints validation for user inputs</a>.<br />
<pre class="prettyprint">@RequestParam String middlename</pre>
- Accept <b>mandatory</b> parameter in variable <b class="inlineCode">middlename</b>. If parameter is not present in request then spring will throw <b class="inlineCode">MissingServletRequestParameterException</b>.<br />
<pre class="prettyprint">@RequestParam(required = false) String lastname</pre>
- Accept <b>optional</b> parameter in variable <b class="inlineCode">lastname</b>.<br />
<br />
<b><span style="font-size: large;">Exception Handling
</span></b><br />
For exception <b class="inlineCode">org.springframework.web.bind.MissingServletRequestParameterException</b> and <b class="inlineCode">javax.validation.ConstraintViolationException</b>, spring will send <b>500 (Internal Server Error)</b> in response so we'll catch those exception and send customized response.<br />
<br />
<b><span style="font-size: large;">Source code (RestExceptionHandler.java)</span></b><br />
Used to catch exception thrown.<br />
<pre class="prettyprint">import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
/**
* @author javaQuery
* @since2018-02-01
*/
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice()
public class RestExceptionHandler extends ResponseEntityExceptionHandler{
@Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
String error = ex.getParameterName() + " parameter is missing.";
return new ResponseEntity<Object>(new ErrorResponse<>(Arrays.asList(error)), HttpStatus.BAD_REQUEST);
}
/**
* Exception thrown when {@link org.springframework.validation.annotation.Validated} is used in controller.
* @param ex
* @param request
* @return
*/
@ExceptionHandler(ConstraintViolationException.class)
protected ResponseEntity<?> handleConstraintViolationException(ConstraintViolationException ex, HttpServletRequest request) {
try {
List<String> messages = ex.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());
return new ResponseEntity<>(new ErrorResponse<>(messages), HttpStatus.BAD_REQUEST);
} catch (Exception e) {
return new ResponseEntity<>(new ErrorResponse<>(Arrays.asList(ex.getMessage())), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
</pre>
<b><span style="font-size: large;">Source code (ErrorResponse.java)</span></b><br />
Used to wrap the error message for response.<br />
<pre class="prettyprint">import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
/**
* @author javaQuery
* @since 2018-02-01
*
* @param <T>
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class ErrorResponse<T> {
private List<T> errors = new ArrayList<>(1);
public ErrorResponse(List<T> errors) {
this.errors = errors;
}
public List<T> getErrors() {
return errors;
}
}
</pre>
<hr />
<b><span style="font-size: large;">Request/Response</span></b><br />
<table class="request-response">
<thead>
<tr>
<td>cURL GET <a class="externalLink" href="http://localhost:8080/api/hello" target="_blank">http://localhost:8080/api/hello</a></td>
</tr>
</thead>
<tbody>
<tr>
<td><pre>-code 400
-body {"errors":["firstname parameter is missing."]}</pre>
</td>
</tr>
</tbody>
</table>
<table class="request-response">
<thead>
<tr>
<td>cURL GET <a class="externalLink" href="http://localhost:8080/api/hello?firstname=&middlename=v" target="_blank">http://localhost:8080/api/hello?firstname=&middlename=v</a></td>
</tr>
</thead>
<tbody>
<tr>
<td><pre>-code 400
-body {"errors":["firstname length must be between 1 and 5"]}</pre>
</td>
</tr>
</tbody>
</table>
<table class="request-response">
<thead>
<tr>
<td>cURL GET <a class="externalLink" href="http://localhost:8080/api/hello?firstname=vicky&middlename=v" target="_blank">http://localhost:8080/api/hello?firstname=vicky&middlename=v</a></td>
</tr>
</thead>
<tbody>
<tr>
<td><pre>-code 200
-body Hello vicky v {lastname-is-optional}</pre>
</td>
</tr>
</tbody>
</table>
<table class="request-response">
<thead>
<tr>
<td>cURL GET <a class="externalLink" href="http://localhost:8080/api/hello?firstname=vicky&middlename=v&lastname=thakor" target="_blank">http://localhost:8080/api/hello?firstname=vicky&middlename=v&lastname=thakor</a></td>
</tr>
</thead>
<tbody>
<tr>
<td><pre>-code 200
-body Hello vicky v thakor</pre>
</td>
</tr>
</tbody>
</table>
</div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-31444497259233050562018-02-01T00:09:00.000+05:302018-02-18T09:51:31.557+05:30Creating first rest api in spring-boot<div dir="ltr" style="text-align: left;" trbidi="on">
<div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-TevOgPVC2dE/WnILAnucRVI/AAAAAAAAGU0/OlrnoLsf2fs9aKpm9_BGEqk5R54gUCZbgCLcBGAs/s1600/spring-boot.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="spring-boot" border="0" data-original-height="300" data-original-width="700" src="https://1.bp.blogspot.com/-TevOgPVC2dE/WnILAnucRVI/AAAAAAAAGU0/OlrnoLsf2fs9aKpm9_BGEqk5R54gUCZbgCLcBGAs/s1600/spring-boot.png" title="spring-boot" /></a></div>
Today we are going to learn how to create rest api in spring-boot. This example is created using <a class="externalLink" href="https://gradle.org/" target="_blank">gradle</a>, if you are not familiar with how to setup gradle project in eclipse follow the steps stated in <a class="externalLink" href="http://www.javaquery.com/2017/01/setup-first-gradle-project-in-eclipse.html" target="_blank">Setup first gradle project in eclipse</a><br />
<br />
<b><span style="font-size: large;">build.gradle</span></b><br />
update your <b class="inlineCode">build.gradle</b> as follow and refresh the project, gradle will download the required dependencies(jar files).<br />
<pre class="prettyprint">buildscript {
ext {
springBootVersion = '1.5.7.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
}
</pre>
<br />
<b><span style="font-size: large;">Source code (HelloWorldController.java)</span></b><br />
Spring follows Model-View-Controller so we'll use widely used package structure and filenames. Now create package like <b>com.example.package</b><b class="inlineCode">.rest.controller</b><br />
<pre class="prettyprint">import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author javaQuery
* @since 2018-01-31
* @github https://github.com/javaquery/spring-boot-examples
*/
@RestController
@RequestMapping("/api")
public class HelloWorldController {
/**
* This will send Hello World in response with HTTP status code 200.
* @return
*/
@GetMapping("/helloworld")
public ResponseEntity sayHello(){
/* return response */
return ResponseEntity.ok("Hello World");
}
}
</pre>
Lets quickly understand annotations used in <b class="inlineCode">HelloWorldController.java
</b><br />
<br />
<ul style="text-align: left;">
<li><b>@RestController</b> - To denote class will be service as rest service</li>
<li><b>@RequestMapping("/api")</b> - default/root path for all apis created under <b class="inlineCode">HelloWorldController.java</b></li>
<li><b>@GetMapping("/helloworld")</b> - <b class="inlineCode">sayHello</b> method will serve for GET http request made for path /api/helloworld</li>
</ul>
<br />
<b><span style="font-size: large;">Source code (Application.java)</span></b><br />
Create Application.java (main-class) in package best suited your project,
<br />
<pre class="prettyprint">import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
/**
* @author javaQuery
* @since 2018-01-31
* @github https://github.com/javaquery/spring-boot-examples
*/
@SpringBootApplication
@ComponentScan(basePackages = { "com.javaquery.examples.springboot.rest" })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
</pre>
Lets quickly understand annotations used in <b class="inlineCode">Application.java</b>
<br />
<br />
<ul style="text-align: left;">
<li><b>@SpringBootApplication</b> - denotes entry point of spring-boot application</li>
<li><b>@ComponentScan</b> - files under given package(s) are part/component of spring application so spring will process the annotations.</li>
</ul>
<div>
Now run <b class="inlineCode">Application.java</b> like any other java application with main method. It'll start local server and your rest API is ready to test. Open up <a class="externalLink" href="localhost:8080/api/helloworld" target="_blank">localhost:8080/api/helloworld</a> in your browser.<br />
<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://4.bp.blogspot.com/-YIEqggukeWM/WnIMlDLQR9I/AAAAAAAAGVA/AF0o10yYf8YjHzUJ8I6Xkz44L3RqEzfCgCLcBGAs/s1600/first-spring-boot-rest-api-project-structure.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" data-original-height="273" data-original-width="353" src="https://4.bp.blogspot.com/-YIEqggukeWM/WnIMlDLQR9I/AAAAAAAAGVA/AF0o10yYf8YjHzUJ8I6Xkz44L3RqEzfCgCLcBGAs/s1600/first-spring-boot-rest-api-project-structure.png" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Project Structure</td></tr>
</tbody></table>
<br />
Source code is also available on my github repository: <a class="externalLink" href="https://github.com/javaquery/spring-boot-examples">https://github.com/javaquery/spring-boot-examples</a>. You can also check spring tutorials on <a href="http://www.javaquery.com/p/spring-tutorials.html" class="externalLink">http://www.javaquery.com/p/spring-tutorials.html</a> and new you can do <a href="http://www.javaquery.com/2018/02/passing-and-validating-requestparam-in.html" target="_blank" class="externalLink">Passing and validating RequestParam in spring-boot rest api</a><br />
<br /></div>
</div>
</div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-42073497211314291772017-11-01T13:21:00.001+05:302017-11-01T13:22:55.205+05:30What is the difference between HQL and Criteria in Hibernate?<div dir="ltr" style="text-align: left;" trbidi="on">
<b>HQL (Hibernate Query Language)</b><br />
<br />
<ul style="text-align: left;">
<li>HQL can be used to perform <b class="inlineCode">SELECT</b>, <b class="inlineCode">INSERT</b>, <b class="inlineCode">UPDATE</b>, <b class="inlineCode">DELETE</b>.</li>
<li>SQL injection possible if not used parameterized query.</li>
<li><b>SELECT STATEMENT</b>: You've to manually write the long queries, take care of where and other syntax.</li>
</ul>
<br />
<b>Criteria</b><br />
<br />
<ul style="text-align: left;">
<li>Criteria can be used to perform only <b class="inlineCode">SELECT</b>.</li>
<li>SQL injection is not possible with Criteria because hibernate will take care of it while generating SQL query.</li>
<li><b>SELECT STATEMENT</b>: Criteria interface comes with handy methods and take care of where and other syntax.</li>
</ul>
<br />
<div>
These are the basic difference between <b>HQL (Hibernate Query Language)</b> and <b>Criteria</b>. Do comment if other important difference is there.<br />
<br />
Check out the <a href="https://stackoverflow.com/questions/4401240/hibernate-criteria-vs-hql-which-is-faster/4770549#4770549" target="_blank" class="externalLink">stackoverflow</a> thread for performance of Hibernate Criteria vs HQL: which is faster?</div><br/>
</div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-73073852614285452092017-07-24T21:45:00.001+05:302017-07-24T21:45:55.825+05:30Hibernate one to many mapping example [Annotation]<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: left;">
We are going to understand hibernate one-to-many relationship on following table structure...</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
<b>country</b> table holds <b>one-to-many</b> relationship with <b>state</b> table. <b>Where relationship id resides in state table</b>.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-fseG8RrLnKM/WXF7i0V06JI/AAAAAAAAGSw/uHAZfJ8aRMMiZPkcEFqO2fj4gcL4h0SvgCLcBGAs/s1600/One%2Bto%2Bmany%2Bhibernate%2Bmapping.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Hibernate One to Many mapping" border="0" data-original-height="296" data-original-width="520" src="https://1.bp.blogspot.com/-fseG8RrLnKM/WXF7i0V06JI/AAAAAAAAGSw/uHAZfJ8aRMMiZPkcEFqO2fj4gcL4h0SvgCLcBGAs/s1600/One%2Bto%2Bmany%2Bhibernate%2Bmapping.png" title="Hibernate One to Many mapping" /></a></div>
<br />
Before we see the complete code, lets first understand how to define relationship in code.<br />
<br />
<b>Country.java, State.java</b><br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://4.bp.blogspot.com/-OtpIPkJMRCg/WXWWm3o7vJI/AAAAAAAAGTI/FGlGPaDi8ZQifKE3RjjS9X6V0mBkL2yFgCLcBGAs/s1600/One%2BTo%2BMany%2BHibernate.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="one to many hibernate" border="0" data-original-height="277" data-original-width="656" src="https://4.bp.blogspot.com/-OtpIPkJMRCg/WXWWm3o7vJI/AAAAAAAAGTI/FGlGPaDi8ZQifKE3RjjS9X6V0mBkL2yFgCLcBGAs/s1600/One%2BTo%2BMany%2BHibernate.png" title="one to many hibernate" /></a></div>
<br />
<span style="font-size: large;"><b>Source code (Country.java)</b></span><br />
<pre class="prettyprint">import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
/**
* @author javaQuery
* @date 11th April, 2017
* @Github: https://github.com/javaquery/Examples
*/
@Entity
@Table(name = "country")
public class Country implements Serializable {
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@OneToMany(mappedBy = "country" /*, fetch = FetchType.LAZY*/)
private Set<State> states = new HashSet<State>();
//getter-setter
}
</pre>
<br />
<b><span style="font-size: large;">Source code (State.java)
</span></b><br />
<pre class="prettyprint">import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* @author javaQuery
* @date 15th June, 2017
* @Github: https://github.com/javaquery/Examples
*/
@Entity
@Table(name = "state")
public class State implements Serializable{
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "country_id")
private Country country;
@Column(name = "name")
private String name;
//getter-setter
}
</pre>
<br />
<b><span style="font-size: large;">Source code (OneToManyMappingExample.java)</span></b><br />
<pre class="prettyprint">import com.javaquery.bean.Country;
import com.javaquery.bean.State;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* Hibernate one to many example.
*
* @author javaQuery
* @date 15th June, 2017
* @Github: https://github.com/javaquery/Examples
*/
public class OneToManyMappingExample {
public static void main(String[] args) {
try {
/* Create hibernate configuration. */
Configuration configuration = new Configuration();
configuration.configure("com\\javaquery\\database\\hibernate\\hibernate.cfg.xml");
/* Open session and begin database transaction for database operation. */
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Country country = session.load(Country.class, 1L);
if(!country.getStates().isEmpty()){
for (State state: country.getStates()) {
System.out.println(state.getName());
}
}else{
System.out.println("No states found!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
</pre>
<br />
<b><span style="font-size: large;">Output</span></b><br />
<pre class="prettyprint">Hibernate:
select
country0_.id as id1_1_0_,
country0_.name as name2_1_0_
from
country country0_
where
country0_.id=?
Hibernate:
select
states0_.country_id as country_3_3_0_,
states0_.id as id1_3_0_,
states0_.name as name2_3_1_
from
state states0_
where
states0_.country_id=?
Banglore
Gujarat
Mumbai
</pre>
</div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0tag:blogger.com,1999:blog-5655258176117800735.post-12633474952122531272017-06-13T09:19:00.000+05:302017-06-13T09:19:16.430+05:30Hibernate one to one mapping example [Annotation]<div dir="ltr" style="text-align: left;" trbidi="on">
We all understand <b>one-to-one</b> relation in database but when it comes to Hibernate I always stuck at which annotation to use and where should I place it?<br />
<br />
We are going to understand the hibernate <b>one-to-one</b> relationship on following table structure.<br />
- <b>country</b> table holds the one-to-one relationship with <b>languages</b> table. <b>Where relationship id resides in country table</b>.<br />
- <b>country</b> table holds the one-to-one relationship with <b>capital</b> table. <b>Where relationship id resides in capital table</b>.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-l7NwVWKkAH8/WP7HnOG0_-I/AAAAAAAAGQs/t7MREvANoL82St_kuW7Z520g_uieCtPOgCLcB/s1600/One%2Bto%2BOne%2B%252B%2BHibernate%2B%252B%2BTable%2BStructure%2B%252BMySQL.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://1.bp.blogspot.com/-l7NwVWKkAH8/WP7HnOG0_-I/AAAAAAAAGQs/t7MREvANoL82St_kuW7Z520g_uieCtPOgCLcB/s1600/One%2Bto%2BOne%2B%252B%2BHibernate%2B%252B%2BTable%2BStructure%2B%252BMySQL.png" /></a></div>
<br />
Before we see the complete code, lets first understand how to define relationship in code.<br />
<br />
<b>Country.java (country - languages)</b><br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-ehVIvSaCtGk/WTYluJey20I/AAAAAAAAGRo/GXQzgw0Hri4erMkKPDVyWQgIbui3UsIjgCLcB/s1600/hibernate%2B%252Bone%2Bto%2Bone%2B%252B%2Bcountry%2B%252B%2Blanguages.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="203" data-original-width="465" src="https://2.bp.blogspot.com/-ehVIvSaCtGk/WTYluJey20I/AAAAAAAAGRo/GXQzgw0Hri4erMkKPDVyWQgIbui3UsIjgCLcB/s1600/hibernate%2B%252Bone%2Bto%2Bone%2B%252B%2Bcountry%2B%252B%2Blanguages.png" /></a></div>
<br />
<b>Capital.java (country - capital)</b><br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-z6SDv7h5HWQ/WTYl1n9ig3I/AAAAAAAAGRs/XEXEOmWE7U8CN80BuFocVJowAUwKtkBiQCLcB/s1600/hibernate%2B%252Bone%2Bto%2Bone%2B%252B%2Bcapital%2B%252B%2Bcountry.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="207" data-original-width="402" src="https://1.bp.blogspot.com/-z6SDv7h5HWQ/WTYl1n9ig3I/AAAAAAAAGRs/XEXEOmWE7U8CN80BuFocVJowAUwKtkBiQCLcB/s1600/hibernate%2B%252Bone%2Bto%2Bone%2B%252B%2Bcapital%2B%252B%2Bcountry.png" /></a></div>
<br />
<b><span style="font-size: large;">Source code (Country.java)</span></b><br />
<pre class="prettyprint">import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
/**
* @author javaQuery
* @date 11th April, 2017
* @Github: https://github.com/javaquery/Examples
*/
@Entity
@Table(name = "country")
public class Country implements Serializable {
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@OneToOne(cascade = CascadeType.ALL, mappedBy = "country")
private Capital capital;
@OneToOne
@JoinColumn(name = "primary_language_id", referencedColumnName = "id")
private Language language;
//getter-setter
}
</pre>
<br />
<b><span style="font-size: large;">Source code (Language.java)</span></b><br />
<pre class="prettyprint">import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author javaQuery
* @date 1th April, 2017
* @Github: https://github.com/javaquery/Examples
*/
@Entity
@Table(name = "languages")
public class Language implements Serializable{
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@Column(name = "language")
private String language;
//getter-setter
}
</pre>
<br />
<b><span style="font-size: large;">Source code (Capital.java)</span></b><br />
<pre class="prettyprint">import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
/**
* @author javaQuery
* @date 11th April, 2017
* @Github: https://github.com/javaquery/Examples
*/
@Entity
@Table(name = "capital")
public class Capital implements Serializable{
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@OneToOne
@JoinColumn(referencedColumnName = "id", name = "country_id")
private Country country;
//getter-setter
}
</pre>
<br />
<b><span style="font-size: large;">Source code (OneToOneMappingExample.java)</span></b><br />
<pre class="prettyprint">import com.javaquery.bean.Country;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* @author javaQuery
* @date 11th April, 2017
* @Github: https://github.com/javaquery/Examples
*/
public class OneToOneMappingExample {
public static void main(String[] args) {
try {
/* Create hibernate configuration. */
Configuration configuration = new Configuration();
configuration.configure("com\\javaquery\\database\\hibernate\\hibernate.cfg.xml");
/* Open session and begin database transaction for database operation. */
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Country country = session.load(Country.class, 1L);
System.out.println(country);
} catch (Exception e) {
e.printStackTrace();
}
}
}
</pre>
<br />
<b><span style="font-size: large;">Output</span></b><br />
<pre class="prettyprint">Hibernate:
select
country0_.id as id1_1_0_,
country0_.primary_language_id as primary_3_1_0_,
country0_.name as name2_1_0_,
language1_.id as id1_2_1_,
language1_.language as language2_2_1_,
capital2_.id as id1_0_2_,
capital2_.country_id as country_3_0_2_,
capital2_.name as name2_0_2_
from
country country0_
left outer join
languages language1_
on country0_.primary_language_id=language1_.id
left outer join
capital capital2_
on country0_.id=capital2_.country_id
where
country0_.id=?
Country{id=1, name=India, capital=Capital{id=2, name=Delhi}, language=Language{id=2, language=Hindi}}
</pre>
</div>
<div class="blogger-post-footer">http://www.javaquery.com</div>Vicky Thakorhttp://www.blogger.com/profile/16098584321464927171noreply@blogger.com0