<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>My Cute Blog</title>
	<atom:link href="http://mycuteblog.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://mycuteblog.com/</link>
	<description>Learn through Experience</description>
	<lastBuildDate>Tue, 10 Oct 2023 15:45:29 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.3</generator>

<image>
	<url>https://mycuteblog.com/wp-content/uploads/2013/11/cropped-social-logo-32x32.png</url>
	<title>My Cute Blog</title>
	<link>https://mycuteblog.com/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Convert Java LocalDateTime to ZonedDateTime</title>
		<link>https://mycuteblog.com/convert-java-localdatetime-to-zoneddatetime/</link>
					<comments>https://mycuteblog.com/convert-java-localdatetime-to-zoneddatetime/#respond</comments>
		
		<dc:creator><![CDATA[Sadupa Wijeratne]]></dc:creator>
		<pubDate>Fri, 17 Feb 2023 15:02:27 +0000</pubDate>
				<category><![CDATA[java]]></category>
		<guid isPermaLink="false">https://mycuteblog.com/?p=903</guid>

					<description><![CDATA[<p>Here is how you can convert Java LocalDateTime to ZonedDatime. Java LocalDateTime store only date time information without any timezone information. You can convert it...</p>
<p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Here is how you can convert Java LocalDateTime to ZonedDatime.</p>



<p class="wp-block-paragraph">Java LocalDateTime store only date time information without any timezone information. You can convert it to a ZonedTime with time zone information.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault())
          .withZoneSameInstant(ZoneOffset.UTC);
</pre></div><p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mycuteblog.com/convert-java-localdatetime-to-zoneddatetime/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Fix for hibernate Legacy-style query parameters no longer supported</title>
		<link>https://mycuteblog.com/fix-for-hibernate-legacy-style-query-parameters-no-longer-supported/</link>
					<comments>https://mycuteblog.com/fix-for-hibernate-legacy-style-query-parameters-no-longer-supported/#respond</comments>
		
		<dc:creator><![CDATA[Sadupa Wijeratne]]></dc:creator>
		<pubDate>Thu, 23 Jan 2020 07:08:18 +0000</pubDate>
				<category><![CDATA[java]]></category>
		<category><![CDATA[Spring]]></category>
		<guid isPermaLink="false">https://mycuteblog.com/?p=890</guid>

					<description><![CDATA[<p>You may have encountered following error if you are migrating hibernate to version 5.x from an older version, This happens due to changes in hibernate...</p>
<p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">You may have encountered following error if you are migrating hibernate to version 5.x from an older version,</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
org.hibernate.QueryException: Legacy-style query parameters (`?`) are no longer supported; use JPA-style ordinal parameters (e.g., `?1`) instead
</pre></div>


<p class="wp-block-paragraph">This happens due to changes in hibernate HQL parameters of latest versions. Here is a quick fix to overcome this issue</p>



<p class="wp-block-paragraph">Simply replace ‘<strong>?</strong>’ with ‘<strong>?0</strong>’ in your HQL query. For example consider following query,<br></p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: sql; title: ; notranslate">
from Customer where id= ?
</pre></div>


<p class="wp-block-paragraph">You may fix this query as below,</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: sql; title: ; notranslate">
from Customer where id= ?0
</pre></div><p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mycuteblog.com/fix-for-hibernate-legacy-style-query-parameters-no-longer-supported/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to setup Lets Encrypt SSL on Amazon Linux</title>
		<link>https://mycuteblog.com/aws-lets-encrypt/</link>
					<comments>https://mycuteblog.com/aws-lets-encrypt/#respond</comments>
		
		<dc:creator><![CDATA[Sadupa Wijeratne]]></dc:creator>
		<pubDate>Tue, 20 Aug 2019 12:56:10 +0000</pubDate>
				<category><![CDATA[AWS]]></category>
		<category><![CDATA[Certbot]]></category>
		<category><![CDATA[Free SSL]]></category>
		<category><![CDATA[Lets Encrypt]]></category>
		<guid isPermaLink="false">http://mycuteblog.com/?p=867</guid>

					<description><![CDATA[<p>Here is a step by step guide on how to setup Lets Encrypt free SSL certificate on an AWS EC2 instance with Amazon linux OS....</p>
<p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Here is a step by step guide on how to setup <a href="https://letsencrypt.org">Lets Encrypt </a>free SSL certificate on an AWS EC2 instance with Amazon linux OS. <a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://certbot.eff.org/" target="_blank">Cerbot</a> client is used to generate the certificates.</p>



<p class="wp-block-paragraph">Currently Lets Encrypt does not officially supports for Amazon Linux OS. But you can use Certbot client in debug mode to install a free SSL certificate on your AWS EC2 instance.</p>



<h2 class="wp-block-heading">Installing Certbot client</h2>



<p class="wp-block-paragraph">Execute following commands to install Certbot client</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; auto-links: false; gutter: false; title: ; notranslate">
wget https://dl.eff.org/certbot-auto
sudo mv certbot-auto /usr/local/bin/certbot-auto
sudo chown root /usr/local/bin/certbot-auto
sudo chmod 0755 /usr/local/bin/certbot-auto
</pre></div>


<h2 class="wp-block-heading">Generating a SSL certificate from Lets Encrypt using Certbot</h2>



<p class="wp-block-paragraph">Execute following command to generate a SSL certificate from Lets Encrypt. Make sure to replace your website path and domain.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; auto-links: false; gutter: false; title: ; wrap-lines: false; notranslate">
sudo /usr/local/bin/certbot-auto certonly --debug --webroot -w /var/www/html/&lt;your_website_path&gt; -d &lt;your_domain&gt;
</pre></div>


<p class="wp-block-paragraph">First of all this command installs a set of libraries in your AWS EC2 instance which are required to generate SSL certificates.</p>



<p class="wp-block-paragraph">Make sure to provide a valid email address during the process to ensure you get email alerts from Lets Encrypt regarding the status of your SSL certificate.</p>



<p class="wp-block-paragraph">Finally certbot will generate certificate files required to enable SSL on your website. You may find them in following path,</p>



<pre class="wp-block-code"><code>/etc/letsencrypt/live/&lt;your_domain&gt;/</code></pre>



<p class="wp-block-paragraph"><code>privkey.pem</code> : the private key for your certificate.<br><code>fullchain.pem</code>: the certificate file used in most server software.<br><code>chain.pem</code> : used for OCSP stapling in Nginx &gt;=1.3.7.<br><code>cert.pem</code> : server certificate</p>



<h2 class="wp-block-heading">Configuring Apache web server to use SSL certificates</h2>



<p class="wp-block-paragraph">Next we have to configure Apache web server to use generated SSL certificates.</p>



<p class="wp-block-paragraph">First of all make sure you have installed <em>mod_ssl</em> in your AWS instance. Use following command to install mod_ssl,</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; auto-links: false; gutter: false; title: ; notranslate">
sudo yum install mod24_ssl
</pre></div>


<p class="wp-block-paragraph">Then add following lines in your Apache configuration file(httpd.conf) to enable SSL.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; auto-links: false; gutter: false; title: ; wrap-lines: false; notranslate">
&lt;VirtualHost *:443&gt;
     DocumentRoot /var/www/&lt;your_domain&gt;
     ServerName &lt;your_domain&gt;
     
     SSLEngine on
     SSLCertificateFile /etc/letsencrypt/live/&lt;your_domain&gt;/cert.pem
     SSLCertificateKeyFile /etc/letsencrypt/live/&lt;your_domain&gt;/privkey.pem
     SSLCertificateChainFile /etc/letsencrypt/live/&lt;your_domain&gt;/chain.pem
&lt;/VirtualHost&gt;
</pre></div>


<p class="wp-block-paragraph">Restart Apache web server using following command</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
sudo service httpd restart
</pre></div>


<h2 class="wp-block-heading">Opening 443 port in AWS EC2 instance for HTTPS</h2>



<p class="wp-block-paragraph">Then we have to make sure port 443 of the EC2 instance is opened in your AWS security settings.</p>



<ol class="wp-block-list">
<li>Log in to <a href="http://console.aws.amazon.com" target="_blank" rel="noreferrer noopener" aria-label=" (opens in a new tab)">AWS console</a></li>



<li>Go to Services &gt; EC2</li>



<li>On the left navigation, under <strong>Network &amp; Security </strong>go to <strong>Security Groups</strong>.</li>



<li>Select the appropriate security group which governs your EC2 instance.</li>



<li>Select <strong>Inbound</strong> tab</li>



<li>Add a rule to open 443 port for TCP traffic</li>
</ol>



<figure class="wp-block-image"><img decoding="async" width="1024" height="45" src="http://mycuteblog.com/wp-content/uploads/2019/08/aws-open-443-port-for-ssl-1024x45.png" alt="AWS open 443 port for SSL" class="wp-image-875" srcset="https://mycuteblog.com/wp-content/uploads/2019/08/aws-open-443-port-for-ssl-1024x45.png 1024w, https://mycuteblog.com/wp-content/uploads/2019/08/aws-open-443-port-for-ssl-300x13.png 300w, https://mycuteblog.com/wp-content/uploads/2019/08/aws-open-443-port-for-ssl-768x34.png 768w, https://mycuteblog.com/wp-content/uploads/2019/08/aws-open-443-port-for-ssl.png 1069w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading">Test SSL certificate</h2>



<p class="wp-block-paragraph">Visit https://&lt;your_domain&gt; to verify the SSL enabled website</p>



<h2 class="wp-block-heading">Add cron to auto renew Lets Encrypt SSL certificate</h2>



<p class="wp-block-paragraph">You can use Certbot to automatically renew Lets Encrypt SSL certificate. Edit linux crontab and add following line. This would setup a crontab to check and renew SSL certificate if required.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
crontab -e
</pre></div>

<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
15 0,12 * * * /usr/local/bin/certbot-auto renew &gt;/dev/null 2&gt;&amp;1
</pre></div>


<p class="wp-block-paragraph"></p>
<p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mycuteblog.com/aws-lets-encrypt/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Amazon S3 sync script</title>
		<link>https://mycuteblog.com/amazon-s3-sync-script/</link>
					<comments>https://mycuteblog.com/amazon-s3-sync-script/#comments</comments>
		
		<dc:creator><![CDATA[Admin My Cute Blog]]></dc:creator>
		<pubDate>Wed, 16 Aug 2017 17:38:31 +0000</pubDate>
				<category><![CDATA[AWS]]></category>
		<guid isPermaLink="false">http://mycuteblog.com/?p=816</guid>

					<description><![CDATA[<p>Here is a step by step guide on how to backup your data to amazon S3. At end of this tutorial you will be able...</p>
<p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Here is a step by step guide on how to backup your data to amazon S3. At end of this tutorial you will be able to create a bash script to sync your data to amazon S3.</p>



<h2 class="wp-block-heading">Create a S3 bucket</h2>



<ol class="wp-block-list">
<li>Log in to your AWS account and go to S3.</li>



<li>Create a new bucket providing a unique name (just use the default settings for now).</li>
</ol>



<h2 class="wp-block-heading">Create a user for s3 access</h2>



<p class="wp-block-paragraph">For security purpose let’s create a separate user for S3 access.</p>



<ol class="wp-block-list">
<li>Go to aws IAM</li>



<li>Go to users</li>



<li>Click ‘Add user’</li>



<li>Enter a name</li>



<li>Chose only ‘Programmatic access’</li>



<li>Next go to permissions and select ‘Attach existing policies directly’</li>



<li>Grant ‘AmazonS3FullAccess’ policy to user</li>



<li>Download credentials.cvs file on the final step</li>
</ol>



<h2 class="wp-block-heading">Amazon CLI configuration</h2>



<p class="wp-block-paragraph">Let’s configure an aws profile to use credentials we have created.<br>First install AWS CLI according to following guide,<br><a href="http://docs.aws.amazon.com/cli/latest/userguide/installing.html" target="_blank" rel="noopener">http://docs.aws.amazon.com/cli/latest/userguide/installing.html</a></p>



<p class="wp-block-paragraph">Issue following command to verify your AWS CLI setup.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
aws --version
</pre></div>


<p class="wp-block-paragraph">If you get the CLI version you are ready to go!</p>



<p class="wp-block-paragraph">Once you have successfully installed, open a command prompt and issue following command to create a AWS CLI profile.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
aws configure --profile my-s3
</pre></div>


<p class="wp-block-paragraph">You can use any name for the profile.</p>



<p class="wp-block-paragraph">You will be asked for your credentials and region. Provide all your details correctly.</p>



<h2 class="wp-block-heading">Script to backup files to amazon S3</h2>



<p class="wp-block-paragraph">Use following bash script to backup your data to amazon S3.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
#!/bin/bash
aws_profile=my-s3
backup_path=/home/me/backup
bucket_name=my-backup

aws s3 sync $backup_path s3://$bucket_name --storage-class=STANDARD_IA --profile=$aws_profile
</pre></div>


<p class="wp-block-paragraph">You can find more details about these options from: <a href="http://docs.aws.amazon.com/cli/latest/reference/s3/sync.html" target="_blank" rel="noopener">http://docs.aws.amazon.com/cli/latest/reference/s3/sync.html</a></p>
<p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mycuteblog.com/amazon-s3-sync-script/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>H2 database example using hibernate and Spring Boot</title>
		<link>https://mycuteblog.com/h2-database-example-hibernate-spring-boot/</link>
					<comments>https://mycuteblog.com/h2-database-example-hibernate-spring-boot/#comments</comments>
		
		<dc:creator><![CDATA[Sadupa Wijeratne]]></dc:creator>
		<pubDate>Sun, 13 Nov 2016 17:09:50 +0000</pubDate>
				<category><![CDATA[H2 Database]]></category>
		<category><![CDATA[h2 database]]></category>
		<category><![CDATA[spring boot]]></category>
		<guid isPermaLink="false">http://mycuteblog.com/?p=753</guid>

					<description><![CDATA[<p>Here is a H2 database example using Hibernate and Spring Boot. This example shows you how to create, read, update and delete a record in H2 database.</p>
<p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>&nbsp;</p>
<p>Here is a H2 database example using Hibernate and Spring Boot. This example shows you how to create, read, update and delete a record in H2 database. I have used maven to build the project.</p>
<p>Download full source code &gt; <div class="wp-block-button">
<a  data-e-Disable-Page-Transition="true" class="dlm-download-link dlm-download-default wp-block-button__link wp-element-button" title="Version 1.0.0" href="https://mycuteblog.com/download/849/?tmstv=1793180611" rel="nofollow" id="download-link-849" data-redirect="false" >
	H2 example source code	(<span class="dlm-download-count-value">11584 downloads</span>
	)
</a>
</div>
</p>
<p>If you are new to hibernate you can read my <a href="http://mycuteblog.com/hibernate4-spring4-maven-example/">Spring Hibernate tutorial</a>.</p>
<h1>Introduction to H2 Database</h1>
<p>H2 is an open source embedded database built on java ships in a single .jar file. Therefore you can easily embed h2 database into your application. H2 Database has a built in web based console that you can use to interact with the database. You can use H2 database as a in-memory database, embedded database or network database.</p>
<p>You can find more details about H2 Database from <a href="http://www.h2database.com/html/main.html" target="_blank" rel="noopener">H2 Database official website</a></p>
<h2>H2 Database example application</h2>
<p>This example application saves request time in a H2 database for each GET request.<br />
<img fetchpriority="high" decoding="async" class="alignnone size-full wp-image-782" src="http://mycuteblog.com/wp-content/uploads/2016/11/h2-example-project-structure.png" alt="h2 example project structure" width="338" height="365" srcset="https://mycuteblog.com/wp-content/uploads/2016/11/h2-example-project-structure.png 338w, https://mycuteblog.com/wp-content/uploads/2016/11/h2-example-project-structure-278x300.png 278w" sizes="(max-width: 338px) 100vw, 338px" /></p>
<h2>.pom file</h2>
<p>First of all here are the maven dependencies for spring boot to use H2 Database and Hibernate</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

    &lt;groupId&gt;com.mycuteblog&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-example&lt;/artifactId&gt;
    &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;

    &lt;parent&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
        &lt;version&gt;1.3.6.RELEASE&lt;/version&gt;
    &lt;/parent&gt;

    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;com.h2database&lt;/groupId&gt;
            &lt;artifactId&gt;h2&lt;/artifactId&gt;
            &lt;version&gt;${h2.version}&lt;/version&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;

    &lt;!--create an executable jar--&gt;
    &lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;

&lt;/project&gt;
</pre>
<h2>Model Class</h2>
<p>ApiRequest.java class to store api request data.</p>
<pre class="brush: java; title: ; notranslate">
@Entity
@Table(name = &quot;api_request&quot;)
public class ApiRequest {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column(name=&quot;request_time&quot;)
    private Date requestTime;

    public ApiRequest() {
    }

    public ApiRequest(Date requestTime) {
        this.requestTime = requestTime;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Date getRequestTime() {
        return requestTime;
    }

    public void setRequestTime(Date requestTime) {
        this.requestTime = requestTime;
    }
}
</pre>
<h2>DAO class</h2>
<p>ApiRequestDao.java class contains methods for CRUD operations with H2 Database</p>
<pre class="brush: java; title: ; notranslate">
@Repository
public class ApiRequestDao {
 @PersistenceContext
 private EntityManager entityManager;

 
 public void create(ApiRequest apiRequest) {
 entityManager.persist(apiRequest);
 }

 
 public void update(ApiRequest apiRequest) {
 entityManager.merge(apiRequest);
 }

 
 public ApiRequest getApiRequestById(long id) {
 return entityManager.find(ApiRequest.class, id);
 }

 
 public void delete(long id) {
 ApiRequest apiRequest = getApiRequestById(id);
 if (apiRequest != null) {
 entityManager.remove(apiRequest);
 }
 }
</pre>
<h2>Service class</h2>
<p>ApiRequestService.java acts between DAO and our controller</p>
<pre class="brush: java; title: ; notranslate">
@Transactional
public class ApiRequestService {

@Autowired
 private ApiRequestDao apiRequestDao;

 public void create(ApiRequest apiRequest) {
 apiRequestDao.create(apiRequest);
 }
}
</pre>
<h2>Controller class</h2>
<p>ApiRequestController.java is the spring web controller which receives the http GET request an process.</p>
<pre class="brush: java; title: ; notranslate">
@RestController
@EnableAutoConfiguration
public class ApiRequestController {

    @Autowired
    private ApiRequestService apiRequestService;

    private static final Logger logger = LoggerFactory.getLogger(ApiRequestController.class);

    @RequestMapping(value = &quot;/&quot;, produces = MediaType.APPLICATION_JSON_VALUE)
    public Map&amp;amp;lt;String, String&amp;amp;gt; getHome() {
        logger.info(&quot;Api request received&quot;);

        Map&amp;amp;lt;String, String&amp;amp;gt; response = new HashMap&amp;amp;lt;String, String&amp;amp;gt;();
        try {
            ApiRequest apiRequest = new ApiRequest(new Date());
            apiRequestService.create(apiRequest);
            response.put(&quot;status&quot;, &quot;success&quot;);
        } catch (Exception e) {
            logger.error(&quot;Error occurred while trying to process api request&quot;, e);
            response.put(&quot;status&quot;, &quot;fail&quot;);
        }

        return response;
    }
}
</pre>
<h2>Main method</h2>
<p>We use main method in WebApplication.java to run the application</p>
<pre class="brush: java; title: ; notranslate">
@SpringBootApplication
public class WebApplication {

    public static void main(String&#x5B;] args) {
        SpringApplication.run(WebApplication.class, args);
    }
}
</pre>
<h2>Property file</h2>
<p>application.properties file contains all the required configurations to connect h2 database and run Spring Boot</p>
<pre class="brush: plain; title: ; notranslate">
server.port = 8080
java.version=1.7

#spring.datasource.url = jdbc:h2:mem:app_db;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.url = jdbc:h2:file:~/h2/app_db;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username = sa
spring.datasource.password =
spring.datasource.driverClassName = org.h2.Driver
spring.jpa.hibernate.ddl-auto = update
</pre>
<h2>H2 Database console</h2>
<p>This is an optional step. Add this class if you wish to enable the h2 database console within your app. Once you add this, H2 database console will be available at <strong>http://localhost:8080/console</strong>.</p>
<pre class="brush: plain; title: ; notranslate">
@Configuration
public class WebConfiguration {
    @Bean
    ServletRegistrationBean h2servletRegistration(){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean( new WebServlet());
        registrationBean.addUrlMappings(&quot;/console/*&quot;);
        return registrationBean;
    }
}
</pre>
<p>That&#8217;s all. Build the project and run using <strong>mvn spring-boot:run</strong> command. Visit following url from your browser to record a api call.<br />
<strong>http://localhost:8080</strong></p>
<p>Download full source code &gt; <div class="wp-block-button">
<a  data-e-Disable-Page-Transition="true" class="dlm-download-link dlm-download-default wp-block-button__link wp-element-button" title="Version 1.0.0" href="https://mycuteblog.com/download/849/?tmstv=1793180611" rel="nofollow" id="download-link-849" data-redirect="false" >
	H2 example source code	(<span class="dlm-download-count-value">11584 downloads</span>
	)
</a>
</div>
</p>
<p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mycuteblog.com/h2-database-example-hibernate-spring-boot/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>Spring task scheduler (cron job) example</title>
		<link>https://mycuteblog.com/spring-task-scheduler-cron-job-example/</link>
					<comments>https://mycuteblog.com/spring-task-scheduler-cron-job-example/#comments</comments>
		
		<dc:creator><![CDATA[Sadupa Wijeratne]]></dc:creator>
		<pubDate>Mon, 09 Feb 2015 18:33:47 +0000</pubDate>
				<category><![CDATA[Spring]]></category>
		<guid isPermaLink="false">http://mycuteblog.com/?p=697</guid>

					<description><![CDATA[<p>Spring framework has built in support for scheduled tasks. Here are some examples of spring cron jobs using both annotations and xml configurations.</p>
<p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph"><br>Spring framework has built in support for scheduled tasks. Here are some examples of spring cron jobs using both annotations and xml configurations.</p>



<p class="wp-block-paragraph">Download full example &gt; <div class="wp-block-button">
<a  data-e-Disable-Page-Transition="true" class="dlm-download-link dlm-download-default wp-block-button__link wp-element-button" title="Version 1.0.0" href="https://mycuteblog.com/download/847/?tmstv=1793180611" rel="nofollow" id="download-link-847" data-redirect="false" >
	spring cron example	(<span class="dlm-download-count-value">10127 downloads</span>
	)
</a>
</div>




<h2 class="wp-block-heading">@Scheduled Annotation</h2>



<p class="wp-block-paragraph">You can use&nbsp;<strong>@Scheduled</strong> annotation to schedule a task very easily. Below are four&nbsp;simple examples to show how to run cron jobs using spring annotations.</p>



<p class="wp-block-paragraph">Annotation.java</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
package com.mycuteblog.spring.schedule;

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@EnableScheduling
public class Annotation {
 @Scheduled(fixedDelay = 5000)
 public void fixedDelayTask() {
 System.out.println(new Date() + " This runs in a fixed delay");
 }

 @Scheduled(fixedRate = 6000)
 public void fixedRateTask() {
 System.out.println(new Date() + " This runs in a fixed rate");
 }

 @Scheduled(fixedRate = 7000, initialDelay = 2000)
 public void fixedRateWithInitialDelayTask(){
 System.out.println(new Date() + " This runs in a fixed delay with a initial delay");
 }

 @Scheduled(cron = "10 * * * * *")
 public void cronTask(){
 System.out.println(new Date() + " This runs in a cron schedule");
 }
}
</pre></div>


<p class="wp-block-paragraph"><strong>fixedDelay: </strong>Run tasks with a fixed delay(in example it&#8217;s 5 seconds) between last task end time and next task start time. For example, if task starts at 11:00:00 and it takes 3 seconds to execute next task starts at 11:00:08.</p>



<p class="wp-block-paragraph"><strong>fixedRate: </strong>Run tasks with a fixed rate of given time. For example in above example<br>fixedRateTask() is called every 6 seconds. (ie: 11:00:00, 11:00:06, 11:00:12, &#8230;)</p>



<p class="wp-block-paragraph"><strong>initialDelay</strong>: This can be used with above examples. This property sets delay for first time run. For example, if program starts at 11:00:00 fixedRateWithInitialDelayTask() will run at 11:00:02, 11:00:09, 11:00:16, &#8230;</p>



<p class="wp-block-paragraph"><strong>cron:</strong> This can be any cron expression.</p>



<p class="wp-block-paragraph">output</p>



<figure class="wp-block-image"><img decoding="async" width="544" height="137" src="http://mycuteblog.com/wp-content/uploads/2015/02/spring-cron-job-demo.jpg" alt="spring cron job demo output" class="wp-image-719" srcset="https://mycuteblog.com/wp-content/uploads/2015/02/spring-cron-job-demo.jpg 544w, https://mycuteblog.com/wp-content/uploads/2015/02/spring-cron-job-demo-300x76.jpg 300w" sizes="(max-width: 544px) 100vw, 544px" /></figure>



<h2 class="wp-block-heading">xml Configuration</h2>



<p class="wp-block-paragraph">A cron job can be set using xml configurations too. Following example shows how you can set above cron jobs using xml.</p>



<p class="wp-block-paragraph">Xml.java</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
package com.mycuteblog.spring.schedule;

import java.util.Date;

public class Xml {
public void xmlFixedDelayTask() {
System.out.println(new Date() + " This task runs in fixed delay by xml configuration");
}

public void xmlFixedRateTask() {
System.out.println(new Date() + " This task runs in fixed rate by xml configuration");
}

public void xmlCronTask() {
System.out.println(new Date() + " This task runs in a cron schedule by xml configuration");
}
}

</pre></div>


<p class="wp-block-paragraph">spring.xml</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
xmlns:task=&quot;http://www.springframework.org/schema/task&quot;
xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/springcontext.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd&quot;&gt;
&lt;context:component-scan base-package=&quot;com.mycuteblog.spring&quot; /&gt;

&lt;bean id=&quot;xmlScheduledTasks&quot; class=&quot;com.mycuteblog.spring.schedule.Xml&quot; /&gt;

&lt;task:scheduler id=&quot;taskScheduler&quot; pool-size=&quot;10&quot; /&gt;

&lt;task:scheduled-tasks&gt;
&lt;task:scheduled ref=&quot;xmlScheduledTasks&quot; method=&quot;xmlFixedDelayTask&quot; fixed-delay=&quot;8000&quot;/&gt;
&lt;task:scheduled ref=&quot;xmlScheduledTasks&quot; method=&quot;xmlFixedRateTask&quot; fixed-rate=&quot;10000&quot;/&gt;
&lt;task:scheduled ref=&quot;xmlScheduledTasks&quot; method=&quot;xmlCronTask&quot; cron=&quot;15 * * * * *&quot;/&gt;
&lt;/task:scheduled-tasks&gt;

&lt;/beans&gt;
</pre></div>


<p class="wp-block-paragraph">I have used maven to build the project. Here is the pom.xml configuration.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;
 xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
 xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
 &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

 &lt;groupId&gt;com.mycuteblog&lt;/groupId&gt;
 &lt;artifactId&gt;spring-schedule&lt;/artifactId&gt;
 &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;

 &lt;dependencies&gt;
 &lt;dependency&gt;
 &lt;groupId&gt;org.springframework&lt;/groupId&gt;
 &lt;artifactId&gt;spring-context&lt;/artifactId&gt;
 &lt;version&gt;4.0.6.RELEASE&lt;/version&gt;
 &lt;/dependency&gt;
 &lt;/dependencies&gt;
 
&lt;!--configurations to run project standalone--&gt;
&lt;/project&gt;
</pre></div>


<p class="wp-block-paragraph">Finally here is the main class to test above examples.</p>



<p class="wp-block-paragraph">SpringScheduleDemo.java</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
package com.mycuteblog.spring.schedule;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringScheduleDemo {
 public static void main(String&#x5B;] args) {
 ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
 }
}
</pre></div>


<p class="wp-block-paragraph">output<br><img loading="lazy" decoding="async" class="alignnone size-full wp-image-721" src="http://mycuteblog.com/wp-content/uploads/2015/02/spring-xml-cron-job-example.jpg" alt="spring xml cron job example" width="587" height="91" srcset="https://mycuteblog.com/wp-content/uploads/2015/02/spring-xml-cron-job-example.jpg 587w, https://mycuteblog.com/wp-content/uploads/2015/02/spring-xml-cron-job-example-300x47.jpg 300w" sizes="auto, (max-width: 587px) 100vw, 587px" /></p>



<p class="wp-block-paragraph">Download full example &gt; <div class="wp-block-button">
<a  data-e-Disable-Page-Transition="true" class="dlm-download-link dlm-download-default wp-block-button__link wp-element-button" title="Version 1.0.0" href="https://mycuteblog.com/download/847/?tmstv=1793180611" rel="nofollow" id="download-link-847" data-redirect="false" >
	spring cron example	(<span class="dlm-download-count-value">10127 downloads</span>
	)
</a>
</div>

<p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mycuteblog.com/spring-task-scheduler-cron-job-example/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
			</item>
		<item>
		<title>How to send an email in a bash script</title>
		<link>https://mycuteblog.com/how-to-send-an-email-in-a-bash-script/</link>
					<comments>https://mycuteblog.com/how-to-send-an-email-in-a-bash-script/#respond</comments>
		
		<dc:creator><![CDATA[Sadupa Wijeratne]]></dc:creator>
		<pubDate>Sat, 15 Nov 2014 16:48:46 +0000</pubDate>
				<category><![CDATA[Bash Scripts]]></category>
		<guid isPermaLink="false">http://mycuteblog.com/?p=686</guid>

					<description><![CDATA[<p>You can send an email in a bash script using mutt command. Here is how you can send an email with an attachment to multiple recipients using a linux shell script.</p>
<p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">You can send an email in a bash script using <strong>mutt</strong> command. Here I have explained how you can send an email with an attachment to multiple recipients using a linux shell script.</p>



<p class="wp-block-paragraph">Here&nbsp;is the format of the script.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
echo &quot;&lt;message body&gt;&quot; | mutt -s &quot;&lt;subject&gt;&quot; -a &quot;&lt;optional attachment&gt;&quot; -e &quot;my_hdr From:&lt;from address&gt;&quot; -- &lt;recipients list separated by space&gt;
</pre></div>


<p class="wp-block-paragraph">Below&nbsp;is a sample bash script using the above code format.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: bash; title: ; notranslate">
subject="Email from bash"
body="This email was sent using a bash script"
from="me@example.com"
to="you@example.com other@example.com"
fileAttachment="/tmp/test.txt"

echo "Sending email..."
echo "$body" | mutt -s "$subject" -a "$fileAttachment" -e "my_hdr From:$from" -- $to
echo "Email sent to: $to"
</pre></div>


<p class="wp-block-paragraph">Additionally you can use following parameters,</p>



<ul class="wp-block-list">
<li>-c carbon copy (Cc)</li>



<li>-b blind carbon copy (Bcc)</li>
</ul>



<p class="wp-block-paragraph">You can view the full parameter list in <a href="http://www.mutt.org/doc/manual/manual-6.html" target="_blank" rel="noopener">official mutt website</a>.</p>
<p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mycuteblog.com/how-to-send-an-email-in-a-bash-script/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Hibernate4 + spring4 + maven example</title>
		<link>https://mycuteblog.com/hibernate4-spring4-maven-example/</link>
					<comments>https://mycuteblog.com/hibernate4-spring4-maven-example/#respond</comments>
		
		<dc:creator><![CDATA[Sadupa Wijeratne]]></dc:creator>
		<pubDate>Tue, 19 Aug 2014 17:15:36 +0000</pubDate>
				<category><![CDATA[java]]></category>
		<category><![CDATA[hibernate4]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[spring4]]></category>
		<guid isPermaLink="false">http://mycuteblog.com/?p=666</guid>

					<description><![CDATA[<p>Here is an example using hibernate4, spring4 and maven. Learn how to do simple create, read, update and delete operations using hibernate.</p>
<p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Here is an example using hibernate4, spring4 and maven. I have described how you can do simple create, read, update and delete operations using hibernate.&nbsp; I have used hibernate annotations for this example.</p>



<p class="wp-block-paragraph">Download source code -&gt; <div class="wp-block-button">
<a  data-e-Disable-Page-Transition="true" class="dlm-download-link dlm-download-default wp-block-button__link wp-element-button" title="Version 1.0" href="https://mycuteblog.com/download/845/?tmstv=1793180611" rel="nofollow" id="download-link-845" data-redirect="false" >
	Hibernate4 example source code	(<span class="dlm-download-count-value">7752 downloads</span>
	)
</a>
</div>




<p class="wp-block-paragraph"><span style="text-decoration: underline;">directory structure</span></p>



<figure class="wp-block-image"><img loading="lazy" decoding="async" width="364" height="438" src="http://mycuteblog.com/wp-content/uploads/2014/08/hibernate-example-directory-structure.png" alt="hibernate example directory structure" class="wp-image-671" srcset="https://mycuteblog.com/wp-content/uploads/2014/08/hibernate-example-directory-structure.png 364w, https://mycuteblog.com/wp-content/uploads/2014/08/hibernate-example-directory-structure-249x300.png 249w" sizes="auto, (max-width: 364px) 100vw, 364px" /></figure>



<h2 class="wp-block-heading">Maven Configuration</h2>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;
         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

    &lt;groupId&gt;com.mycuteblog&lt;/groupId&gt;
    &lt;artifactId&gt;hibernate4&lt;/artifactId&gt;
    &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;

    &lt;properties&gt;
        &lt;spring.version&gt;4.0.6.RELEASE&lt;/spring.version&gt;
        &lt;hibernate.version&gt;4.3.6.Final&lt;/hibernate.version&gt;
        &lt;mysql.version&gt;5.1.6&lt;/mysql.version&gt;
    &lt;/properties&gt;

    &lt;dependencies&gt;
        &lt;!-- Spring 4 dependencies --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-core&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-context&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-orm&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;

        &lt;!-- Hibernate 4 dependencies --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
            &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt;
            &lt;version&gt;${hibernate.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
            &lt;artifactId&gt;hibernate-c3p0&lt;/artifactId&gt;
            &lt;version&gt;${hibernate.version}&lt;/version&gt;
        &lt;/dependency&gt;

        &lt;!--mysql--&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;mysql&lt;/groupId&gt;
            &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
            &lt;version&gt;${mysql.version}&lt;/version&gt;
        &lt;/dependency&gt;

    &lt;/dependencies&gt;

    &lt;!--additional configurations to run project standalone--&gt;
&lt;/project&gt;

</pre></div>


<h2 class="wp-block-heading">User Class</h2>



<p class="wp-block-paragraph">This class contains all required fields for the users table. Hibernate will create users table automatically using these fields.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
@Entity
@Table(name = &quot;users&quot;)
public class User {
    @Id
    @Column(name = &quot;id&quot;)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Column(name = &quot;user_id&quot;)
    private long userId;
    @Column(name = &quot;first_name&quot;)
    private String firstName;
    @Column(name = &quot;last_name&quot;)
    private String lastName;
    @Column(name = &quot;age&quot;)
    private int age;
    @Column(name = &quot;created_date&quot;)
    private Date createdDate;

   &lt;-- getters and setters --&gt;
}

</pre></div>


<h2 class="wp-block-heading">Hibernate session factory class</h2>



<p class="wp-block-paragraph">This class is used to get current session from the session factory. Session factory is injected through spring.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class HibernateSessionFactoryImpl implements HibernateSessionFactory {

    private SessionFactory sessionFactory;

    @Override
    public Session getSession() {
        return this.sessionFactory.getCurrentSession();
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
}

</pre></div>


<h2 class="wp-block-heading">User dao</h2>



<p class="wp-block-paragraph">This class contains all CRUD operations for user class.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    HibernateSessionFactory hibernateSessionFactory;

    @Override
    public boolean addUser(User user) {
        Session session = hibernateSessionFactory.getSession();
        session.save(user);
        return true;
    }

    @Override
    public User getUser(long userId) {
        Session session = hibernateSessionFactory.getSession();
        User user = (User) session.createCriteria(User.class)
                .add(Restrictions.eq("userId", userId))
                .uniqueResult();

        return user;
    }

    @Override
    public boolean updateUser(User user) {
        Session session = hibernateSessionFactory.getSession();
        session.update(user);
        return true;
    }

    @Override
    public boolean deleteUser(User user) {
        Session session = hibernateSessionFactory.getSession();
        session.delete(user);
        return true;
    }
}

</pre></div>


<h2 class="wp-block-heading">User Controller</h2>



<p class="wp-block-paragraph">This class handles data using dao class. You can implement your business logic here.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
@Transactional
public class UserControllerImpl implements UserController {

    @Autowired
    private UserDao userDao;

    @Override
    public boolean addUser(User user) {
        return userDao.addUser(user);
    }

    @Override
    public User getUser(long userId) {
        return userDao.getUser(userId);
    }

    @Override
    public boolean updateUser(User user) {
        return userDao.updateUser(user);
    }

    @Override
    public boolean deleteUser(User user) {
        return userDao.deleteUser(user);
    }
}

</pre></div>


<h2 class="wp-block-heading">Hibernate configuration</h2>



<p class="wp-block-paragraph">This file contains all required hibernate configurations. I have used cp30 for data pooling.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xmlns:tx=&quot;http://www.springframework.org/schema/tx&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
  
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd&quot;&gt;

    &lt;bean id=&quot;dataSource&quot;
          class=&quot;com.mchange.v2.c3p0.ComboPooledDataSource&quot; destroy-method=&quot;close&quot;&gt;
        &lt;property name=&quot;driverClass&quot; value=&quot;com.mysql.jdbc.Driver&quot;/&gt;
        &lt;property name=&quot;jdbcUrl&quot; value=&quot;jdbc:mysql://localhost:3306/hibernate_example?autoReconnect=true&quot;/&gt;
        &lt;property name=&quot;user&quot; value=&quot;user&quot;/&gt;
        &lt;property name=&quot;password&quot; value=&quot;password&quot;/&gt;

        &lt;!-- C3P0 properties  refer: http://www.mchange.com/projects/c3p0/ --&gt;
        &lt;property name=&quot;acquireIncrement&quot; value=&quot;2&quot;/&gt;
        &lt;property name=&quot;minPoolSize&quot; value=&quot;20&quot;/&gt;
        &lt;property name=&quot;maxPoolSize&quot; value=&quot;50&quot;/&gt;
        &lt;property name=&quot;maxIdleTime&quot; value=&quot;600&quot;/&gt;
    &lt;/bean&gt;

    &lt;!-- Hibernate session factory --&gt;
    &lt;bean id=&quot;sessionFactory&quot; class=&quot;org.springframework.orm.hibernate4.LocalSessionFactoryBean&quot;&gt;
        &lt;property name=&quot;dataSource&quot;&gt;
            &lt;ref bean=&quot;dataSource&quot;/&gt;
        &lt;/property&gt;

        &lt;property name=&quot;hibernateProperties&quot;&gt;
            &lt;props&gt;
                &lt;prop key=&quot;hibernate.dialect&quot;&gt;org.hibernate.dialect.MySQLDialect&lt;/prop&gt;
                &lt;prop key=&quot;hibernate.hbm2ddl.auto&quot;&gt;update&lt;/prop&gt;
            &lt;/props&gt;
        &lt;/property&gt;
        &lt;property name=&quot;packagesToScan&quot; value=&quot;com.mycuteblog.hibernate4&quot;/&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;hibernateSessionFactory&quot; class=&quot;com.mycuteblog.hibernate4.dao.impl.HibernateSessionFactoryImpl&quot;&gt;
        &lt;property name=&quot;sessionFactory&quot; ref=&quot;sessionFactory&quot; /&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;transactionManager&quot;
          class=&quot;org.springframework.orm.hibernate4.HibernateTransactionManager&quot;&gt;
        &lt;property name=&quot;sessionFactory&quot; ref=&quot;sessionFactory&quot;/&gt;
    &lt;/bean&gt;

    &lt;tx:annotation-driven transaction-manager=&quot;transactionManager&quot;/&gt;

&lt;/beans&gt;

</pre></div>


<h2 class="wp-block-heading">Spring configuration</h2>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
  
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd&quot;&gt;

    &lt;context:component-scan base-package=&quot;com.mycuteblog.hibernate4&quot; /&gt;

    &lt;context:annotation-config /&gt;

    &lt;import resource=&quot;classpath:hibernate-config.xml&quot; /&gt;

    &lt;bean name=&quot;userController&quot; class=&quot;com.mycuteblog.hibernate4.controller.impl.UserControllerImpl&quot; /&gt;

&lt;/beans&gt;
</pre></div>


<p class="wp-block-paragraph">Here is the main class which tests all we created above.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
public class HibernateDemo {

    public static void main(String&#x5B;] args){

        ApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml");

        UserController userController = (UserController) context.getBean("userController");

        User user = new User();
        user.setUserId(100);
        user.setFirstName("Foo");
        user.setLastName("Boo");
        user.setAge(25);
        user.setCreatedDate(new Date());

        userController.addUser(user);

        User savedUser = userController.getUser(100);
        System.out.println(savedUser.toString());

        user.setFirstName("Boo");
        user.setLastName("Foo");
        user.setAge(24);
        userController.updateUser(user);

        User updatedUser = userController.getUser(100);
        System.out.println(updatedUser.toString());

        userController.deleteUser(updatedUser);

        User deletedUser = userController.getUser(100);

        if (deletedUser == null){
            System.out.println("user has been deleted from db");
        }

    }
}
</pre></div>


<p class="wp-block-paragraph">Here is the output</p>



<pre class="wp-block-code"><code>User{id=1, userId=100, firstName='Foo', lastName='Boo', age=25, createdDate=2014-08-19 22:26:55.0}
User{id=1, userId=100, firstName='Boo', lastName='Foo', age=24, createdDate=2014-08-19 22:26:55.0}
user has been deleted from db</code></pre>



<p class="wp-block-paragraph">Download source code -&gt; <div class="wp-block-button">
<a  data-e-Disable-Page-Transition="true" class="dlm-download-link dlm-download-default wp-block-button__link wp-element-button" title="Version 1.0" href="https://mycuteblog.com/download/845/?tmstv=1793180611" rel="nofollow" id="download-link-845" data-redirect="false" >
	Hibernate4 example source code	(<span class="dlm-download-count-value">7752 downloads</span>
	)
</a>
</div>

<p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mycuteblog.com/hibernate4-spring4-maven-example/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>log4j2 xml configuration example</title>
		<link>https://mycuteblog.com/log4j2-xml-configuration-example/</link>
					<comments>https://mycuteblog.com/log4j2-xml-configuration-example/#comments</comments>
		
		<dc:creator><![CDATA[Sadupa Wijeratne]]></dc:creator>
		<pubDate>Sat, 26 Jul 2014 05:19:00 +0000</pubDate>
				<category><![CDATA[java]]></category>
		<category><![CDATA[log4j]]></category>
		<category><![CDATA[maven]]></category>
		<guid isPermaLink="false">http://mycuteblog.com/?p=636</guid>

					<description><![CDATA[<p>Here are some sample log4j2 xml configurations. This includes full source code created with maven.</p>
<p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Here are some sample log4j2 xml configurations.</p>



<p class="wp-block-paragraph">These configurations should be included in a file named <strong>log4j2.xml</strong> and placed on the classpath.</p>



<p class="wp-block-paragraph">Download source code &gt; <div class="wp-block-button">
<a  data-e-Disable-Page-Transition="true" class="dlm-download-link dlm-download-default wp-block-button__link wp-element-button" title="Version 1.0" href="https://mycuteblog.com/download/843/?tmstv=1793180611" rel="nofollow" id="download-link-843" data-redirect="false" >
	log4j2 xml configuration source code	(<span class="dlm-download-count-value">12025 downloads</span>
	)
</a>
</div>




<h2 class="wp-block-heading">Console Appender</h2>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;Configuration status=&quot;WARN&quot;&gt;
 &lt;Appenders&gt;
 &lt;Console name=&quot;console&quot; target=&quot;SYSTEM_OUT&quot;&gt;
 &lt;PatternLayout pattern=&quot;&#x5B;%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} &#x5B;%t] %c{1} - %msg%n&quot;/&gt;
 &lt;/Console&gt;
 &lt;/Appenders&gt;
 &lt;Loggers&gt;
 &lt;Root level=&quot;info&quot; additivity=&quot;false&quot;&gt;
 &lt;AppenderRef ref=&quot;console&quot;/&gt;
 &lt;/Root&gt;
 &lt;/Loggers&gt;
&lt;/Configuration&gt;
</pre></div>


<p class="wp-block-paragraph">Console appender prints all logs to console. Here is a sample output using above configuration.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
&#x5B;INFO ] 2014-07-23 22:04:31.447 &#x5B;main] LogDemo - Hello world - info log
</pre></div>


<h2 class="wp-block-heading">Daily Rolling File Appender</h2>



<p class="wp-block-paragraph">Daily rolling file appender prints logs to a file. Difference between file appender and daily rolling file appender is, daily rolling file appender creates a log file per day.</p>



<p class="wp-block-paragraph">This configuration is widely used in commercial systems due to following&nbsp; benefits,</p>



<ul class="wp-block-list">
<li>Size of a single log file is smaller</li>



<li>Log analysis is easy</li>



<li>Old log files can be archived or deleted</li>
</ul>



<p class="wp-block-paragraph">Here is a sample log4j2 configuration for a daily rolling appender.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;Configuration status=&quot;debug&quot;&gt;
&lt;Properties&gt;
&lt;Property name=&quot;log-path&quot;&gt;logs&lt;/Property&gt;
&lt;/Properties&gt;

&lt;Appenders&gt;
&lt;RollingFile name=&quot;file-log&quot; fileName=&quot;${log-path}/mycuteblog-info.log&quot;
filePattern=&quot;${log-path}/mycuteblog-info-%d{yyyy-MM-dd}.log&quot;&gt;
&lt;PatternLayout&gt;
&lt;pattern&gt;&#x5B;%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} &#x5B;%t] %c{1} - %msg%n&lt;/pattern&gt;
&lt;/PatternLayout&gt;
&lt;Policies&gt;
&lt;TimeBasedTriggeringPolicy interval=&quot;1&quot; modulate=&quot;true&quot;/&gt;
&lt;/Policies&gt;
&lt;/RollingFile&gt;

&lt;Console name=&quot;console&quot; target=&quot;SYSTEM_OUT&quot;&gt;
&lt;PatternLayout pattern=&quot;&#x5B;%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} &#x5B;%t] %c{1} - %msg%n&quot;/&gt;
&lt;/Console&gt;
&lt;/Appenders&gt;
&lt;Loggers&gt;
&lt;Logger name=&quot;com.mycuteblog&quot; level=&quot;info&quot; additivity=&quot;false&quot;&gt;
&lt;appender-ref ref=&quot;file-log&quot; level=&quot;info&quot;/&gt;
&lt;/Logger&gt;
&lt;Root level=&quot;info&quot; additivity=&quot;false&quot;&gt;
&lt;appender-ref ref=&quot;console&quot;/&gt;
&lt;/Root&gt;
&lt;/Loggers&gt;
&lt;/Configuration&gt;
</pre></div>


<h2 class="wp-block-heading">Separate log for error logs</h2>



<p class="wp-block-paragraph">Using following configuration you can have a separate log file for error logs.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;Configuration status=&quot;debug&quot;&gt;
&lt;Properties&gt;
&lt;Property name=&quot;log-path&quot;&gt;logs&lt;/Property&gt;
&lt;/Properties&gt;

&lt;Appenders&gt;
&lt;RollingFile name=&quot;file-log&quot; fileName=&quot;${log-path}/mycuteblog-info.log&quot;
filePattern=&quot;${log-path}/mycuteblog-info-%d{yyyy-MM-dd}.log&quot;&gt;
&lt;PatternLayout&gt;
&lt;pattern&gt;&#x5B;%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} &#x5B;%t] %c{1} - %msg%n&lt;/pattern&gt;
&lt;/PatternLayout&gt;
&lt;Policies&gt;
&lt;TimeBasedTriggeringPolicy interval=&quot;1&quot; modulate=&quot;true&quot;/&gt;
&lt;/Policies&gt;
&lt;/RollingFile&gt;

&lt;Console name=&quot;console&quot; target=&quot;SYSTEM_OUT&quot;&gt;
&lt;PatternLayout pattern=&quot;&#x5B;%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} &#x5B;%t] %c{1} - %msg%n&quot;/&gt;
&lt;/Console&gt;
&lt;/Appenders&gt;
&lt;Loggers&gt;
&lt;Logger name=&quot;com.mycuteblog&quot; level=&quot;info&quot; additivity=&quot;false&quot;&gt;
&lt;appender-ref ref=&quot;file-log&quot; level=&quot;info&quot;/&gt;
&lt;/Logger&gt;
&lt;Root level=&quot;info&quot; additivity=&quot;false&quot;&gt;
&lt;appender-ref ref=&quot;console&quot;/&gt;
&lt;/Root&gt;
&lt;/Loggers&gt;
&lt;/Configuration&gt;
</pre></div>


<h2 class="wp-block-heading">log4j2 full example</h2>



<p class="wp-block-paragraph">Here is&nbsp; a sample java code with all above configurations. I have used maven for dependency management.</p>



<p class="wp-block-paragraph">LogDemo.java</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
package com.mycuteblog.log4j2;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
* Created by sadupa on 7/26/14.
*/
public class LogDemo {

private static final Logger logger = LogManager.getLogger(LogDemo.class.getName());

public static void main(String&#x5B;] args){

logger.debug(&amp;quot;Hello world - debug log&amp;quot;);
logger.info(&amp;quot;Hello world - info log&amp;quot;);
logger.warn(&amp;quot;Hello world - warn log&amp;quot;);
logger.error(&amp;quot;Hello world - error log&amp;quot;);
}
}
</pre></div>


<p class="wp-block-paragraph">log4j2.xml</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;Configuration status=&quot;WARN&quot;&gt;
    &lt;Properties&gt;
        &lt;Property name=&quot;log-path&quot;&gt;logs&lt;/Property&gt;
    &lt;/Properties&gt;
    &lt;Appenders&gt;
        &lt;Console name=&quot;console-log&quot; target=&quot;SYSTEM_OUT&quot;&gt;
            &lt;PatternLayout pattern=&quot;&#x5B;%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} &#x5B;%t] %c{1} - %msg%n&quot;/&gt;
        &lt;/Console&gt;
        &lt;RollingFile name=&quot;trace-log&quot; fileName=&quot;${log-path}/mycuteblog-trace.log&quot;
                     filePattern=&quot;${log-path}/mycuteblog-trace-%d{yyyy-MM-dd}.log&quot;&gt;
            &lt;PatternLayout&gt;
                &lt;pattern&gt;&#x5B;%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} &#x5B;%t] %c{1} - %msg%n&lt;/pattern&gt;
            &lt;/PatternLayout&gt;
            &lt;Policies&gt;
                &lt;TimeBasedTriggeringPolicy interval=&quot;1&quot; modulate=&quot;true&quot;/&gt;
            &lt;/Policies&gt;
        &lt;/RollingFile&gt;
        &lt;RollingFile name=&quot;error-log&quot; fileName=&quot;${log-path}/mycuteblog-error.log&quot;
                     filePattern=&quot;${log-path}/mycuteblog-error-%d{yyyy-MM-dd}.log&quot;&gt;
            &lt;PatternLayout&gt;
                &lt;pattern&gt;&#x5B;%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} &#x5B;%t] %c{1} - %msg%n&lt;/pattern&gt;
            &lt;/PatternLayout&gt;
            &lt;Policies&gt;
                &lt;TimeBasedTriggeringPolicy interval=&quot;1&quot; modulate=&quot;true&quot;/&gt;
            &lt;/Policies&gt;
        &lt;/RollingFile&gt;
    &lt;/Appenders&gt;
    &lt;Loggers&gt;
        &lt;Logger name=&quot;com.mycuteblog.log4j2&quot; level=&quot;debug&quot; additivity=&quot;false&quot;&gt;
            &lt;appender-ref ref=&quot;trace-log&quot; level=&quot;debug&quot;/&gt;
            &lt;appender-ref ref=&quot;error-log&quot; level=&quot;error&quot;/&gt;
            &lt;appender-ref ref=&quot;console-log&quot; level=&quot;debug&quot;/&gt;
        &lt;/Logger&gt;
        &lt;Root level=&quot;info&quot; additivity=&quot;false&quot;&gt;
            &lt;AppenderRef ref=&quot;console-log&quot;/&gt;
        &lt;/Root&gt;
    &lt;/Loggers&gt;
&lt;/Configuration&gt;
</pre></div>


<p class="wp-block-paragraph">pom.xml</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;
         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

    &lt;groupId&gt;com.mycuteblog&lt;/groupId&gt;
    &lt;artifactId&gt;log4j2Demo&lt;/artifactId&gt;
    &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
    &lt;packaging&gt;jar&lt;/packaging&gt;

    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.logging.log4j&lt;/groupId&gt;
            &lt;artifactId&gt;log4j-api&lt;/artifactId&gt;
            &lt;version&gt;2.0&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.logging.log4j&lt;/groupId&gt;
            &lt;artifactId&gt;log4j-core&lt;/artifactId&gt;
            &lt;version&gt;2.0&lt;/version&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;

    &lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
            &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
            &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt;
            &lt;version&gt;2.4&lt;/version&gt;
            &lt;configuration&gt;
                &lt;archive&gt;
                    &lt;manifest&gt;
                        &lt;addClasspath&gt;true&lt;/addClasspath&gt;
                        &lt;mainClass&gt;com.mycuteblog.log4j2.LogDemo&lt;/mainClass&gt;
                        &lt;classpathPrefix&gt;dependency-jars/&lt;/classpathPrefix&gt;
                    &lt;/manifest&gt;
                &lt;/archive&gt;
            &lt;/configuration&gt;
        &lt;/plugin&gt;
        &lt;plugin&gt;
            &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
            &lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt;
            &lt;version&gt;2.5.1&lt;/version&gt;
            &lt;executions&gt;
                &lt;execution&gt;
                    &lt;id&gt;copy-dependencies&lt;/id&gt;
                    &lt;phase&gt;package&lt;/phase&gt;
                    &lt;goals&gt;
                        &lt;goal&gt;copy-dependencies&lt;/goal&gt;
                    &lt;/goals&gt;
                    &lt;configuration&gt;
                        &lt;outputDirectory&gt;
                            ${project.build.directory}/dependency-jars/
                        &lt;/outputDirectory&gt;
                    &lt;/configuration&gt;
                &lt;/execution&gt;
            &lt;/executions&gt;
        &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;
&lt;/project&gt;
</pre></div>


<p class="wp-block-paragraph">Download source code &gt; <div class="wp-block-button">
<a  data-e-Disable-Page-Transition="true" class="dlm-download-link dlm-download-default wp-block-button__link wp-element-button" title="Version 1.0" href="https://mycuteblog.com/download/843/?tmstv=1793180611" rel="nofollow" id="download-link-843" data-redirect="false" >
	log4j2 xml configuration source code	(<span class="dlm-download-count-value">12025 downloads</span>
	)
</a>
</div>




<p class="wp-block-paragraph">Here is the output of above code.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
 &#x5B;DEBUG] 2014-07-26 10:12:50.139 &#x5B;main] LogDemo - Hello world - debug log
 &#x5B;INFO ] 2014-07-26 10:12:50.142 &#x5B;main] LogDemo - Hello world - info log
 &#x5B;WARN ] 2014-07-26 10:12:50.142 &#x5B;main] LogDemo - Hello world - warn log
 &#x5B;ERROR] 2014-07-26 10:12:50.142 &#x5B;main] LogDemo - Hello world - error log
</pre></div><p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mycuteblog.com/log4j2-xml-configuration-example/feed/</wfw:commentRss>
			<slash:comments>12</slash:comments>
		
		
			</item>
		<item>
		<title>Run multiple mysql servers on single machine</title>
		<link>https://mycuteblog.com/run-multiple-mysql-servers-on-single-machine/</link>
					<comments>https://mycuteblog.com/run-multiple-mysql-servers-on-single-machine/#respond</comments>
		
		<dc:creator><![CDATA[Sadupa Wijeratne]]></dc:creator>
		<pubDate>Wed, 02 Jul 2014 16:57:20 +0000</pubDate>
				<category><![CDATA[SQL]]></category>
		<guid isPermaLink="false">http://mycuteblog.com/?p=616</guid>

					<description><![CDATA[<p>Here is how to run multiple mysql instances on the same machine. This will be helpful when you need to run different mysql version on...</p>
<p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-633" src="http://mycuteblog.com/wp-content/uploads/2014/07/mysql.jpg" alt="mysql" width="640" height="408" srcset="https://mycuteblog.com/wp-content/uploads/2014/07/mysql.jpg 640w, https://mycuteblog.com/wp-content/uploads/2014/07/mysql-300x191.jpg 300w" sizes="auto, (max-width: 640px) 100vw, 640px" /></p>
<p>Here is how to run multiple mysql instances on the same machine. This will be helpful when you need to run different mysql version on same computer or have separate mysql servers for each system.</p>
<p>Here I assume you have already installed one instance of mysql. Following steps are for installing another instance of mysql on a linux system.</p>
<p>Download the required mysql version from <a href="http://dev.mysql.com/downloads/mysql/" target="_blank">dev.mysql.com</a></p>
<h3>Create a separate directory for new mysql instance</h3>
<p>We will install new mysql instance on a separate directory. Therefore we can make sure current mysql installation is not affected. This directory will hold mysql databases and other files related to this installation.</p>
<pre class="brush: bash; title: ; notranslate">
sudo mkdir /var/lib/mysql2
cd /var/lib/
chown user.user mysql2</pre>
<p>replace user with your current user name.</p>
<h3>my.conf Configurations</h3>
<p>We have to use some custom configurations for new mysql instance. First copy the existing my.conf file to newly created directory (<a href="http://dev.mysql.com/doc/refman/5.1/en/option-files.html" target="_blank">how to find existing my.cnf file?</a>). Update following settings in the newly copied my.cnf file,</p>
<ul>
<li>port</li>
<li>pid</li>
<li>socket</li>
<li>datadir</li>
</ul>
<p>Here is a sample configuration,</p>
<pre class="brush: plain; title: ; notranslate">
port=3307
datadir=/var/lib/mysql2/
socket=/var/lib/mysql2/mysql.sock
pid=/var/lib/mysql2/mysql.pid </pre>
<p>Make sure to use a separate port number which will not conflict with current system.</p>
<h3>Initializing mysql</h3>
<p>Once you have done the configurations you have to run the install script to setup required initial data for mysql.</p>
<p>Go to the downloaded mysql directory and execute following command,</p>
<pre class="brush: plain; title: ; notranslate">scripts/mysql_install_db --user=mysql --datadir=/var/lib/mysql2/</pre>
<p>Make sure you don&#8217;t run above code with root permissions. That will avoid any permission issue in the future.</p>
<p>If you run the script successfully you will see mysql data files created in /var/lib/mysql2 directory.</p>
<h3>Starting mysql server</h3>
<p>Start mysql server using following command</p>
<pre class="brush: plain; title: ; notranslate">bin/mysqld_safe --user=mysql &amp;</pre>
<h3>Connecting to mysql server</h3>
<p>You can connect to mysql server using following command.</p>
<pre class="brush: plain; title: ; notranslate">mysql -hlocalhost -P3307 -uroot</pre>
<p>Now you can use new mysql server as usual.</p>
<p><a href="https://mycuteblog.com">My Cute Blog</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mycuteblog.com/run-multiple-mysql-servers-on-single-machine/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
