java – Log4j

Background

Playing around with Hibernate got me staring at the screen reviewing console messages; especially SQL statements.

Log4j

Time to implement better logging; mostly instead of having it show up on the console, placing it in log files.

Download

Artifacts

log4j is available here ( https://logging.apache.org/log4j/2.x/download.html ).

Version

The current version is 2.11.2

Download

Please download and extract the files.

I am on Windows and chose apache-log4j-2.11.2-bin.zip.

Project Configuration

Eclipse

This is a simple test and so started a new project.

Project Configuration

In Eclipse, please access the Java Build Path.

Files

  1. log4j-api-2.11.2.jar
  2. log4j-core-2.11.2.jar

Image

Configuration Files

Log4j

Sample

log4j2.property.20190518.0147PM

Java

Outline

  1. Import packages/classes
    • Apache – log4j
      • org.apache.logging.log4j
        • import org.apache.logging.log4j.LogManager;
        • import org.apache.logging.log4j.Logger;
    • Network
      • java.net
        • Import java.net.InetAddress
        • Import java.net.UnknownHostException
  2. Instantiate Logger
    • LogManager.getLogger
  3. Use Logger
    • Invoke Log
      • log.info
      • log.error

Sample


package log4j2;

import java.util.Map;

import java.net.InetAddress;
import java.net.UnknownHostException;

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

public final class hello
{

	private static final Logger log
				= LogManager.getLogger
					(
							log4j2.hello.class
					);

	public static void main(String[] args)
	{

		// TODO Auto-generated method stub
		String computerName = null;

		computerName = getComputerName();

		if (computerName != null)
		{

			computerName = getHostName();

		};

		//computerName = null;

		if (computerName != null)
		{
			log.info("Computer :- " + computerName);
		}
		else
		{

			log.error("Unknown Computer!");

		}

	}

	static private String getHostName()
	{

		String hostname = null;

		try
		{
		    InetAddress addr;
		    addr = InetAddress.getLocalHost();
		    hostname = addr.getHostName();
		}
		catch (UnknownHostException ex)
		{
		    System.out.println("Hostname can not be resolved");
		}

		return (hostname);

	}

	/*
	 *
	 * https://stackoverflow.com/questions/7883542/getting-the-computer-name-in-java
	 */
	static private String getComputerName()
	{
	    Map env = System.getenv();
	    if (env.containsKey("COMPUTERNAME"))
	        return env.get("COMPUTERNAME");
	    else if (env.containsKey("HOSTNAME"))
	        return env.get("HOSTNAME");
	    else
	        return null;
	}

}

Output

Source Control

Git

log4j.2.sample
Link

Summary

A couple of quick points.

A lot of the Log4j sample configuration files available on the Internet are based on the original implementation.

The current version of Log4j is version 2, Log4j2.

Its XML Schema is quite different than Version 1.

Please look for samples that explicitly mention and reference, Log4j2.

 

Java – Set – Method – Remove – Null Exception

Background

Trying to familiarize myself with Collection classes in Java.

With Hibernate being an ORM tool that encapsulates database processes, one has to have a good grasp of records and set operations.

Error

I ran into a blocking error.

It simply read null.

 

Code

Original Code

Java Snippet


Set cities = new HashSet();

for (City city:cities)
{

	if (city != null)
	{

		removeCity(city);

		//Doing this raised Exception
		//Exception Message is null
		cities.remove(city);

	}		

}

Output

Exception


Exception Message is null
StackTrace

Revised Code

Java Snippet


Set cities = new HashSet();

Iterator iterator = cities.iterator();

while (iterator.hasNext())
{

	City city = iterator.next();

	removeCity(city);

	iterator.remove();

}

 

Summary of Change

In the erroring code :-

  1. We iterated the set using the for-each construct
    • Process each node
    • Attempt to remove the processed node via invoking the remove method
      • Hashset.remove
        • Failed
          • null exception

The revised code :-

  1. Instantiated an iterator against the collection
  2. Checked for next node via the hasNext method
  3. If hasNext is positive :-
    • Invoke next against the Iterator, receive back the node
    • Process the node
    • Invoke remove against the Iterator

References

  1. java tutorial
    • Interfaces
      • The Set Interface
        Link
  2. java references
    • java.util
      • java.util.HashSet
        • Class HashSet<E>
          Link
    • java.util
      • java.util.Iterator
        • Interface Iterator<E>
          Link

Hibernate/Annotation – Error – “Schema-validation: missing column”

Background

Adding more functionality to a POJO ( Plain Old Java Object) class that relies on Annotations.

Error

But, here ended up with an error!

Error Message


Schema-validation: missing column [bResetDependantEntityCountryIDOnDelete] in table [dbo.country]
Failed to create sessionFactory object.org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing column [bResetDependantEntityCountryIDOnDelete] in table [dbo.country]
Exception in thread "main" java.lang.ExceptionInInitializerError
        at sakila.helloDB.dbWork(helloDB.java:166)
        at sakila.helloDB.run(helloDB.java:55)
        at sakila.helloDB.main(helloDB.java:42)
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing column [bResetDependantEntityCountryIDOnDelete] in table [dbo.country]
        at org.hibernate.tool.schema.internal.AbstractSchemaValidator.validateTable(AbstractSchemaValidator.java:136)
        at org.hibernate.tool.schema.internal.GroupedSchemaValidatorImpl.validateTables(GroupedSchemaValidatorImpl.java:42)
        at org.hibernate.tool.schema.internal.AbstractSchemaValidator.performValidation(AbstractSchemaValidator.java:89)
        at org.hibernate.tool.schema.internal.AbstractSchemaValidator.doValidation(AbstractSchemaValidator.java:68)
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:192)
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73)
        at org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:309)
        at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:462)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
        at sakila.helloDB.getDBSession(helloDB.java:82)
        at sakila.helloDB.dbWork(helloDB.java:116)
        ... 2 more

Error Image

SchemaValidationMissingColumn.20190516.0828PM.PNG

Code

Outline

  1. “Decorate” variable declaration with the keyword @Transient

Code


    private Boolean bResetDependantEntityCountryIDOnDelete = true;

    public Boolean getResetDependantEntityCountryIDOnDeleteFlag()
    {
        return bResetDependantEntityCountryIDOnDelete;
    }

    public void setResetDependantEntityCountryIDOnDeleteFlag(Boolean value)
    {
    	bResetDependantEntityCountryIDOnDelete = value;
    }

Revision


    //object.org.hibernate.tool.schema.spi.SchemaManagementException:
    //Schema-validation: missing column
    @Transient
    private Boolean bResetDependantEntityCountryIDOnDelete = true;

    public Boolean getResetDependantEntityCountryIDOnDeleteFlag()
    {
        return bResetDependantEntityCountryIDOnDelete;
    }

    public void setResetDependantEntityCountryIDOnDeleteFlag(Boolean value)
    {
    	bResetDependantEntityCountryIDOnDelete = value;
    }

Hibernate – Modeling – Foreign Key Relationships

Background

Wanted to provide a working sample that demonstrates how to use plain old java object ( POJO) files with annotation.

We will simulate a foreign key relationship between city and country.

 

Database Model

location

Model Classes

Outline

Model Class – Country

  1. Table
    • Table Name :- Country
    • Unique Constraint
      • country_id
  2. Columns
    • countryID
      • name=country_ID
      • unique=true
      • nullable=false
      • variable type=short
    • country
      • name=country
      • unique=true
      • nullable=false
      • variable type=short
    • last_update
      • name=last_update
      • unique=false
      • nullable=false
      • variable type=java.sql.Timestamp
  3. Constraint
    • Foreign Key
      • @OneToMany(mappedBy=”country”)
      • private Set<City> cities;

 

Model Class – City

  1. Table
    • Table Name :- City
    • Unique Constraint
      • city_id
  2. Columns
    • city_id
      • name=cityID
      • unique=true
      • nullable=false
      • updatable = false
      • insertable = false
      • variable type=Integer
    • country_id
      • name=country
      • unique=false
      • nullable=false
      • variable type=short
    • city
      • name=city
      • unique=false
      • nullable=false
      • variable type=string
    • last_update
      • name=last_update
      • unique=false
      • nullable=false
      • variable type=java.sql.Timestamp
  3. Constraint
    • Foreign Key
      • @ManyToOne
      • @JoinColumn
        • name=country_id

Classes

Model Class – Country


package sakila;

import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import java.util.Set;

@Entity
@Table(name = "country"
            , uniqueConstraints =
                {
                    @UniqueConstraint(columnNames = "country_ID")
                }
      )

public class Country
{

    @Id
    @Column(name = "country_ID", unique = true, nullable = false)
    private short CountryID;

    @Column(name = "country", unique = false, nullable = false, length = 60)
    private String Country;

    @Column(name = "last_update", unique = false, nullable = true)
    private  Timestamp tsUpdate;    

    public Country()
    {

    }

    @OneToMany(mappedBy="country")
    private Set cities;

    public Timestamp gettsUpdate()
    {
        return tsUpdate;
    }

    public void settsUpdate(Timestamp tsUpdate)
    {
        this.tsUpdate = tsUpdate;
    }

    public short getCountryID()
    {
        return CountryID;
    }

    public void setCountryID(short countryID)
    {
        CountryID = countryID;
    }

    public String getCountry()
    {
        return Country;
    }

    public void setCountry(String country)
    {
        Country = country;
    }

}

Model Class – City


package sakila;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import java.sql.Timestamp;
//import org.hibernate.annotations.OptimisticLockType;

@Entity
@Table(
              name = "city"
            , uniqueConstraints =
                {
                    @UniqueConstraint
                    (
                        columnNames = "city_ID"
                    )
                }
      )

public class City
implements Serializable
{

    private static final long serialVersionUID = -1798070786993154676L;

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column
    (
          name          = "city_ID"
        , unique        = true
        , nullable      = false
        , updatable     = false
        , insertable    = false
    )
    private Integer cityID;

    @Id
    @ManyToOne
    @JoinColumn
    (
          name="country_id"
        , nullable=false
    )
    private Country country;

    @Id
    @Column
    (
          name = "city"
        , unique = false
        , nullable = false
        , length = 60
    )
    private String city;

    @Column
    (
          name = "last_update"
        , unique = false
        , nullable = true
    )
    private  Timestamp tsUpdate;

    // Accessors
    public Timestamp gettsUpdate()
    {
        return tsUpdate;
    }

    public void settsUpdate(Timestamp tsUpdate)
    {
        this.tsUpdate = tsUpdate;
    }

    public Country getCountry()
    {
        return country;
    }

    public void setCountry(Country value)
    {
        country = value;
    }

    public String getCity()
    {
        return city;
    }

    public void setCity(String value)
    {
        city = value;
    }

}

Source Control

GitHub

DanielAdeniji/javaHibernateSQLServerSakila
Link

  1. Model Files
    • Country
    • City

 

Hibernate – Error Message – “Unknown entity”

Background

Learning new tooling is not easy for me.

Error

Image

unknownEntity.20190509.0942AM

Textual

Unknown entity: sakila.Country

Trouble Shooting

Metadata

Entities Registered

Outline

  1. Start a Session or use an existing one
  2. Get Session’s Transaction handle
  3. Start a new transaction
  4. Get Session’s metamodel
  5. Get Metamodel entity list
  6. Iterate Metamodel entity list
  7. Commit Transaction

Code

/*
     * This function lists the entities declared in our session
     * It principally relies on session.getMetaModel.getEntities
     */
    private void entityList
    (
		  Session session
	)
    { 

    	String strEntity;
    	int i;
    	int iNumberofElements;
    	Transaction transaction;
    	Metamodel objEntityManager;
        Set&lt;EntityType&gt; objEntityTypeList;

    	try
        {

        	System.out.println("Retrieve entities ...."); 

        	//Get Session's Transaction
        	transaction
        		= session.getTransaction();

        	//Start Transaction
            transaction.begin();

            //Get MetaModel
            objEntityManager
            	= session.getMetamodel();

            //Get Entities
            objEntityTypeList
            	= objEntityManager.getEntities();

            //get Number of Entities
            iNumberofElements
            	= objEntityTypeList.size();

        	System.out.println
        		(
					CHAR_TAB
					+ "Number of elements is "
					+ iNumberofElements
				); 

        	//reset i
            i = 0;

            //Iterate through collection
            for (javax.persistence.metamodel.EntityType objEntityType:  objEntityTypeList)
            {

            	//increment
            	i = i +1;

            	//Get Entity
            	strEntity = objEntityType.toString();

            	//Display Entity
            	System.out.println
            	(
    				CHAR_TAB + CHAR_TAB
    				+ i
    				+ ") "
            	    + strEntity
        	    ); 

            }

        	System.out.println("Entities Retrieved"); 

        	//Close Transaction
            transaction.commit();

        }

    	catch (Exception ex)
    	{

    		System.out.println(ex.getMessage()); 

            if (session.getTransaction().isActive())
            {
                session.getTransaction().rollback();
            }

        } //Iterate through collection catch

	} //entityList<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>

Similar Errors

@OneToOne or @ManyToOne on [entity] references an unknown entity

Image

@OneToOne or @ManyToOne on sakila.City.country references an unknown entity.

Text


Failed to create sessionFactory object.org.hibernate.AnnotationException:
@OneToOne or @ManyToOne on sakila.City.country references an unknown entity: sakila.Country

@OneToOne or @ManyToOne on sakila.City.country references an unknown entity: sakila.Country

Summary

Was able to confirm that the entities were not registering correctly.

And, moved on from there and sought help from a real Java developer.

Hibernate – SQL Server – Exercise – 01

Background

Wanted to share source code for a sample helloDB Script that I am trying to use as I self teach Hibernate.

Outline

  1. Database File
    • DDL
      • Table
        • dbo.Country
  2. Java Source File
    • helloDB.java
  3. Hibernate Configuration File
    • SQLServerSavila.cfg.xml
  4. Entity
    • Country
      • Country.java ( POJO File )
      • Country.hbm.xml ( XML )

Source Code

Database

DDL

Table

Country
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

USE [sakila]
GO

/*
    drop table [dbo].[country];
*/

/*
    truncate table [dbo].[country];
*/

/*
    select *
    from [dbo].[country];
*/
IF NOT EXISTS
(
    SELECT *
    FROM sys.objects
    WHERE object_id = OBJECT_ID(N'[dbo].[country]')
    AND type in (N'U')
)
BEGIN

    CREATE TABLE [dbo].[country]
    (
        [country_id] [smallint] NOT NULL,
        [country] [varchar](50) NOT NULL,
        [last_update] [datetime] NULL

        , constraint [dbo.PK_Country]
          primary key
        (
            [country_id]
        )
    )
    ON [PRIMARY]

END
GO

Source Code

helloDB.java

package sakila;

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

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.List;
import java.util.Set;

public class helloDB
{

	Configuration objConfiguration = null;

	static String CONFIGURATION_FILE_SQLSERVER = "SQLServerSakila.cfg.xml";

	SessionFactory factoryMSSQL = null;

	static String CHAR_TAB = "\t";

	public static void main(String[] args)
	{

		// TODO Auto-generated method stub
		run();

	}

	public static void run()
	{

			helloDB objHelloDB = null;

			objHelloDB = new helloDB();

			try
			{
				objHelloDB.dbWork();
			}
			catch (Exception ex)
			{

				System.out.println(ex.getMessage());

			}

			objHelloDB =null;

	}

    private Session getDBSession()
    {
    	Session session = null;

    	Configuration cfg= new Configuration();

    	cfg.configure(CONFIGURATION_FILE_SQLSERVER);

    	factoryMSSQL
			= cfg.buildSessionFactory();

    	session = factoryMSSQL.openSession(); 

    	//session = factoryMSSQL.getCurrentSession(); 

    	return session;

    }

    void dbWork()
	//throws Exception
    {

    	try
    	{

    		Session session = null;

    		session = getDBSession();

	    	entityList(session);

	    	countryAddList(session);

	    	countryList(session);

	    	session.close();

	    	factoryMSSQL.close();

    	}
		catch (Exception ex)
		{

			System.out.println(ex.getMessage());

			System.err.println("Failed to create sessionFactory object." + ex);

			throw new ExceptionInInitializerError(ex);
		}

    }

    // list all objects
    private void countryList(Session session)
    {

    	List lists;
    	Country       objCountry;

    	String strLog;

		System.out.println("List Countries");

		System.out.println("==============");

    	lists = session.createQuery("from Country").list(); 

    	System.out.println(lists.size()); 

    	for (int i = 0; i < lists.size(); i++)
    	{ 

			objCountry = lists.get(i);

			strLog = CHAR_TAB
						+ objCountry.getCountry()
						+ " "
						+ "("
						+ objCountry.getCountryID()
						+ ")";

			System.out.println(strLog);

    	}	

    }

    private void countryAddList
    (
		Session session
	)
	throws Exception
    {

    	countryAdd(session, 1, "United States of America");
    	countryAdd(session, 33, "France");
    	countryAdd(session, 44, "United Kingdom");
    	countryAdd(session, 55, "Brazil");
    	countryAdd(session, 61, "Australia");

    }

    private void countryAdd
    (
		  Session session
		, int countryID
		, String country
	)
	throws Exception
    {
        try
        {

        	Transaction transaction = session.getTransaction();

            transaction.begin();

            Country objCountry = new Country();

            objCountry.setCountryID(countryID);
            objCountry.setCountry(country);
            objCountry.settsUpdate(new Timestamp(Calendar.getInstance().getTime().getTime()));

            session.persist(objCountry);

            transaction.commit();

        }

    	catch (Exception ex)
    	{

			System.err.println("Failed to Add country " + country);

			System.out.println(ex.getMessage());

            if (session.getTransaction().isActive())
            {
                session.getTransaction().rollback();
            }

        }

	}

    private void entityList
    (
		  Session session
	)
	//throws Exception
    { 

    	String strEntity;
    	int iNumberofElements;
    	Set objEntityTypeList;

    	try
        {

            objEntityTypeList = session.getMetamodel().getEntities();

            iNumberofElements = objEntityTypeList.size();

        	System.out.println("Retrieve entities ...."); 

        	System.out.println(CHAR_TAB + "Number of elements is " + iNumberofElements); 

        	Transaction transaction = session.getTransaction();

            transaction.begin();

            for (javax.persistence.metamodel.EntityType objEntityType:  session.getMetamodel().getEntities())
            {

            	strEntity = objEntityType.toString();

            	System.out.println(CHAR_TAB + CHAR_TAB + "entity name "+strEntity); 

            }

        	System.out.println("Entities Retrieved"); 

            transaction.commit();

        }

    	catch (Exception ex)
    	{

    		System.out.println(ex.getMessage()); 

            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }

            //throw ex;
        }

	}

}

Hibernate Configuration File

SQLServerSavila.cfg.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>

  <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>

  <property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>

  <property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;databaseName=sakila;</property>

  <property name="hibernate.connection.username">sakila</property>

  <property name="hibernate.connection.password">VecRadrI3h</property>

  <!-- JDBC connection pool (use the built-in) -->
  <property 
  	name="connection.pool_size">
  	1
  </property>

  <property name="current_session_context_class">thread</property>

  <!-- Disable the second-level cache  -->
  <property 
  	name="hibernate.cache.use_second_level_cache"> 
  	false
  </property>

  <!-- Echo all executed SQL to stdout -->
  <property name="show_sql">true</property>
  
  <!-- Drop and re-create the database schema on startup -->
  <!-- validate schema on startup -->
 
  <property name="hbm2ddl.auto">validate</property>
  
  <property name="hibernate.default_schema">dbo</property>

 
  <mapping 
  	resource="sakila/Country.hbm.xml"
  	/>
 
  <!-- 
  	 <mapping class="sakila.Employee"/>
	-->
 
 </session-factory>
</hibernate-configuration>

Entity

Country

Country.java ( POJO File )

package sakila;

/*
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
*/

import java.sql.Timestamp;

public class Country
{

	private int CountryID;
	private String Country;
	private Timestamp tsUpdate;

	public Country()
	{

	}

	public Timestamp gettsUpdate()
	{
		return tsUpdate;
	}

	public void settsUpdate(Timestamp tsUpdate)
	{
		this.tsUpdate = tsUpdate;
	}

	public int getCountryID()
	{
		return CountryID;
	}

	public void setCountryID(int countryID)
	{
		CountryID = countryID;
	}

	public String getCountry()
	{
		return Country;
	}

	public void setCountry(String country)
	{
		Country = country;
	}

}

Country.hbm.xml ( HBM.XML File )

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping 
	PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping/hibernate-mapping-3.0.dtd"
>
<hibernate-mapping>

 <class 
 	name="sakila.Country" 
 	schema="dbo" 
 	table="country"
>


  <id 
  		column="country_id" 
  		name="CountryID" 
  		type="short"
  		/>

  <property 
  		column="country" 
  		generated="never" 
  		lazy="false"
   		name="Country" 
   		type="string"
   		/>
   
  <property 
  		column="last_update" 
  		generated="never" 
  		lazy="false"
   		name="tsUpdate" 
   		type="timestamp"
   		/>
   		
 </class>
</hibernate-mapping>

Source Code Control

GitHub

DanielAdeniji/javaHibernateSQLServerSakila
Link

 

Eclipse – Change IDE’s JRE Version

Background

Really fumbling a lot here.

Trying to get the Hibernate Plugin to play well with Eclipse is becoming my fool’s errand.

Wifey

I did not know she had texted.  But, now I know as she is calling.

I could not reach for the phone in time.

But the text read, “When are you getting off work?“.

She is easy.

Her request is always around food.

This time it is pickup seafood. And, don’t forget they close at 9:30 pm.

 

Error Message

As I muddled my way around the Hibernate Wizards confronted with a fresh message.

It read :-

Image

window.hibernateConfigurations.01.20190506.0426PM

Textual

Project ‘helloDBHibernate03’ has higher compiler option than running EclipseHibernate plugins unable to load its classes.
Please decrease the compiler option or run the Eclipse with higher JDK level.

Explanation

I really like mouthful paragraphs that are easy to read and comprehend :-

  1. The error message states my current project’s compiler option is higher than Eclipse’s own JVM.
  2. As a result the Hibernate plugin can not be loaded
  3. To re-mediate
    • Change the project’s compiler option
    • Run Eclipse’s JDK Level

Lineage

I know that the issue is my changing my project’s JDK level.

That move is documented here :-

Eclipse – Changing Targeted JRE
Link

Remediation

I could revert the Project’s JDK level.

or try running Eclipse at a complementary JRE.

GUI

Wanted to do make the transition using the GUI.

But, could not find a way to do so.

Manual

Outline

  1. Ensure you have downloaded and installed the targeted JDK
  2. Configure Eclipse to use targeted JDK
    • Change needs to occur via eclipse.ini

Java Runtime

Java Runtime – v11

Artifact

JRE 11 is available here

artifact.jdk11.20190507.0933AM

Install

Installed JDK 11.

Review Install

The install is targeted at :-

java.install.folder.20190507.0936AM

Review Folder

Noticed :-

  1. Unlike earlier versions :-
    • Bundling
      • We do not have separate installs for JRE and JDK
      • We only have one JDK
    • Naming
      • Folder ( JDK versus JRE )
        • Previous ( < JDK 10 )
          • jre*
        •  New ( >= JDK 10 )
          • jdk*
      • Folder ( Decimal versus Whole)
        • Previous ( < JDK 10 )
          • 1.3
          • 1.8
        •  New ( >= JDK 10 )
          • 10
          • 11

Eclipse

Configuration File

Folder

Please access the eclipse folder

eclipse.winOS.folder.01.20190507.0930AM
eclipse.ini
Outline
  1. Backup eclipse.ini
  2. Modify the following entries
    • vm
      • original
        • -vm
          C:/Program Files/Java/jre1.8.0_181/bin
      • Revised
        • -vm
          C:/Program Files/Java/jdk-11.0.3/bin
    • vmargs
      • original
        • -Dosgi.requiredJavaVersion=1.8
      • revised
        • -Dosgi.requiredJavaVersion=11
    • add-modules
      • original
        • –add-modules=ALL-SYSTEM
          -Dosgi.requiredJavaVersion=1.8
      • revised
        • –add-modules=ALL-SYSTEM
          -Dosgi.requiredJavaVersion=11
Backup File

Please backup the eclipse.ini file.

It is the one we will be modifying.

File – Original

eclipse.revised.1.8.20190507.0953AM

File – Revised

eclipse.revised.11.20190507.0950AM

Validation

Outline

  1. Please restart Eclipse
  2. Use menu to access Eclipse About
    • The “Eclipse About” window appears
    • Please click the “Installation Details” button
    • Please access the “Configuration” Tab
    • The retrieving system Information message appears
    • Waited a few more for the Configuration details to appear

Configuration

v11

Image

jre.version.v11.20190507.1105AM

Text

-vm
C:/Program Files/Java/jdk-11.0.3/bin\server\jvm.dll

 

Dedicated

Life is good once you run into Amy :-

Amy DeGregorio
Baeldung
How to Fix java.lang.UnsupportedClassVersionError
Link