Thursday, October 30, 2014

How to Map a list of strings with JPA/Hibernate annotations ?

Yesterday while working on my project, I got one requirement where I need to store list of Array into the database, I checked on Google, went through various site but didn't get much information. Everyone talks about creating new entity and do onetomany relationship BUT I wanted to create a collection of basic types.

Finally I come across @ElementCollection annotation provided by JPA 2.0 which resolves my problem.

Problem :
Input JSON which we need to store in DB:

{
"schemas": ["urn:scim:schemas:core:1.0", "urn:scim:schemas:extension:enterprise:1.0"]
}
           Where schemas is Array of String.
Solution :


Just add following annotation in your POJO i,e
@ElementCollection
@CollectionTable(name = "SCIM_SCHEMAS", joinColumns = @JoinColumn(name = "SCHEMA_ID"))
@Column(name = "SCIM_SCHEMA")
private List<String> schemas;

It will create the table named "SCIM_SCHEMAS" having columns 'SCHEMA_ID' and 'SCIM_SCHEMA'


For details check section 2.2.5.3.3. Collection of basic types or embeddable objects or feel free to comment :)



Thursday, October 16, 2014

How to create Java Classes using xjc from XML file

This tutorial will demonstrate how can you generate Java Objects from XML documents using xjc tool. The tool “xjc” is used to generate the annotated Java classes from the XSD schema

Suppose I am using below XML file to generate Java Objects i,e
<?xml version="1.0" encoding="UTF-8"?>
<adaptorapp id="application">
<instance id="instance1">
<connectiondetails>
<accesskey>abcde</accesskey>
<secretkey>fghij</secretkey>
</connectiondetails>
</instance>
<instance id="instance2">
<connectiondetails>
<accesskey>klmnop</accesskey>
<secretkey>qrstuvwxyz</secretkey>
</connectiondetails>
</instance>
</adaptorapp>
Now  to generate Java Objects we need to create one xsd file(say "connection.xsd") :
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="adaptorapp" type="AdaptopApp" />
<xs:complexType name="AdaptopApp">
<xs:sequence>
<xs:element name="instance" type="Instance" maxOccurs="unbounded" />
</xs:sequence>
<xs:attribute name="id" type="xs:string" use="required" />
</xs:complexType>
<xs:complexType name="Instance">
<xs:sequence>
<xs:element name="connectiondetail" type="ConnectionDetail" />
</xs:sequence>
<xs:attribute name="id" type="xs:string" use="required" />
</xs:complexType>
<xs:complexType name="ConnectionDetail">
<xs:sequence>
<xs:element name="accesskey" type="xs:string" />
<xs:element name="secretkey" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:schema>
I have written XSD Schema based on my XML file, You can write something similar according to your requirement.

Lets use the 'xjc" tool to generate corresponding Java classes
                xjc.exe connection.xsd
By default, It will generates the Java classes in a directory named "generated".


Please let me know your feedback/queries as comments.

Thursday, October 9, 2014

Hibernate Error - Caused by: org.hibernate.DuplicateMappingException: duplicate import:

In hibernate, You cannot have two classes with the same name in the same or different packages else you will get an error at runtime like


"Caused by: org.hibernate.DuplicateMappingException: duplicate import: ....(try using auto-import="false")"


I have resolved this issue by adding property name on the Entity annotation.
Let us suppose I have Meta class in two different packages "com.database.user" and "com.database.group', you can resolve it as :
package com.database.user
@Entity(name= "com.database.user")
@Table(name="USER_META")
public class Meta

package com.database.group
@Entity(name= "com.database.group")
@Table(name="GROUP_META")
public class Meta

There must be some other ways too to resolve this issue, So please feel free to share it :)





Wednesday, August 13, 2014

How to upgrade ANT in Eclipse ?

To upgrade the ANT into the Eclipse, First you need to download the latest version of ANT anywhere on you machine.
Once you are done with the download then go to
EclipseWindowsPreferencesAntRuntimeAnt Home and Select the downloaded folder.

Now your Eclipse will use the latest version of ANT :)

Wednesday, July 16, 2014

How to exclude properties file from the Jar file

Problem Statement : Suppose your are working on Java Project which uses Maven structure where your source code is under “/src/main/java” and all your configuration files like .properties file or xml file are under “/src/main/resources” and as a final build your final package is a jar but you want without few files from your classpath. Be default Maven plugin adds all the file which comes under resources in jar file.

Solution : You can achieve the above task by using maven-jar-plugin as follows :

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.3</version>
    <configuration>
        <excludes>
            <exclude>**/otp.properties</exclude>
        </excludes>
    </configuration>

</plugin>

Tuesday, July 1, 2014

maven-dependency-plugin (goals “copy-dependencies”, “unpack”) is not supported by m2e

Recently While importing one Maven project into Eclipse(Juno, m2e plug-ins is already installed in Eclipse). I was getting one error in project : maven-dependency-plugin (goals “copy-dependencies”, “unpack”) is not supported by m2e


Reason: Eclipse m2e does not support execution, by copying the below code in the build tag resolve the issue.

Example:

<build>
<COPY_CODE_HERE>
</build>

Code :

<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings
only. It has no influence on the Maven build itself. -->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>

<pluginExecution>
<pluginExecutionFilter>
<groupId>
org.apache.maven.plugins
</groupId>
<artifactId>
maven-antrun-plugin
</artifactId>
<versionRange>
1.7
</versionRange>
<goals>
<goal>run</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>

Save the project and it will resolve the issue, if not then Right click on your project and update Maven(Maven → Update Project... ).


Monday, May 19, 2014

How to upgrade or downgrade data schema ?

I ll continue with this tutorial to show how to upgrade or downgrade the database schema.

Suppose we need to add one more field ManagerAddress in our existing Managers tables, To do this we need to use one feature called Migrations . It allows us to have an ordered set of steps that describe how to upgrade (and downgrade) our database schema.

Each of these steps, known as a migration, contains some code that describes the changes to be applied.
  • Tools → NuGet Package Manager → Package Manager Console
  • Run the Enable-Migrations command in Package Manager Console
The two new file get created under Migrations folder :
  • Configuration.cs : It contains the setting that Migrations will use for migrating ManagingContext.
  • <timestamp>_InitialCreate.cs – This is your first migration, it represents the changes that have already been applied to the database to take it from being an empty database to one that includes the Manager and Employee tables.
Now we will add one more field ManagerAddress to the Manager Model.

public class Manager
{
public int ManagerId { get; set; }
public String ManagerName { get; set; }
public String ManagerAddress { get; set; }
public virtual List<Employee> Employees { get; set; }
}
  • Run the Add-Migration AddManagerAddress in the Package Manager Console.

The Add-Migration command checks for changes since your last migration and scaffolds a new migration with any changes that are found. We need to  give migrations a name; in this case we are calling the migration ‘AddManagerAddress’.

The scaffolded code is saying that we need to add a ManagerAddress column, that can hold string data, to the dbo.Managers table. If needed, we could edit the scaffolded code but that’s not required in this case.

namespace CreateNewDatabase.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AddManagerAddress : DbMigration
{
public override void Up()
{
AddColumn("dbo.Managers", "ManagerAddress", c => c.String());
}
public override void Down()
{
DropColumn("dbo.Managers", "ManagerAddress");
}
}
}

  • Run the Update-Database command in Package Manager Console. This command will apply any pending migrations to the database. Our InitialCreate migration has already been applied so migrations will just apply our new AddManagerAddress migration.
The new ManagerColumn column is now added to the Managers table in the database:



How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...