JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

NetBeans IDE 7.0 Final available for download!

June 11, 2011 by JavaBeat Leave a Comment

NetBeans IDE 7.0

NetBeans™ IDE 7.0 introduces language support for coding to the proposed Java SE 7 specification with the JDK 7 developer preview. Developers can now take advantage of the new language features from Project Coin /JSR 334, with editor support for code completion, hints, and in specific cases converting existing Java SE 6 based code to use the new Java SE 7 based syntax.

The release also provides enhanced integration with the Oracle WebLogic server as well as support for Oracle Database and GlassFish 3.1. The Oracle WebLogic server integration enhancements include fast turnaround when redeploying applications; deploy on save; datasource management; server library configuration; the ability to explore deployed applications and resources, and to view server logs and the admin console from within the IDE.

Additional highlights include Maven 3 and HTML5 editing support; a new GridBagLayout designer for improved Swing GUI development; enhancements to the Java editor, and more.

NetBeans IDE 7.0 is available in English, Brazilian Portuguese, Japanese, Russian, and Simplified Chinese.

Release Highlights

JDK 7

  • Project Coin support
  • Editor enhancements: Code completion, hints

WebLogic Server

  • Streamlined and faster deployment to WebLogic
  • New server runtime node displaying deployed applications and resources

Oracle Database

  • Simplified connection wizard
  • Guided installation to JDBC driver

GlassFish

  • GlassFish 3.1 support
  • Domain restart and log viewer for remote GlassFish

Java

  • Maven 3 support
  • JUnit 4.8.2 integration and various JUnit improvements
  • New improved visual customizer for GridBagLayout

Java EE

  • Improved support for CDI, REST services and Java Persistence
  • Improved editing for Expression Language in JSF, including code completion, refactoring and hints

Web Languages

  • HTML5 editing support
  • JSON formatter

PHP

  • Generate PhpDoc
  • Rename refactoring, Safe Delete Refactoring

C/C++

  • Easy import of project from user’s existing binary
  • New Project type where user’s source files are located on remote system

NetBeans Platform

  • Annotations for generating Action registrations in the layer
  • Performance enhancements & tight integration with Profiler

General

  • Word wrap in Editor
  • Enhanced Profiler integration
  • NetBeans 7.0 Download

Filed Under: NetBeans Tagged With: NetBeans

SAP PP Interview Questions [Press Release – Dreamtech Press]

February 24, 2011 by JavaBeat Leave a Comment

SAP PP Interview Questions

(Hands on tips for cracking the interview)

Description

Technical interviews are largely focused on assessing your knowledge and skills on a specific technology or subject matter. Preparing for a technical job interview could be an uphill task, where you would need to scan voluminous books and material from numerous sources spread across different media. Wouldn’t your efforts be reduced greatly if you get a book specifically devoted towards the technical interviews on the respective technology/subject matter?

A new book by Dreamtech Press, SAP PP Interview Questions (Dreamtech Press, February 23, 2011, INR. 199/-, ISBN: 978-81-7722-796-3) brings to you an economical and time-saving ensemble of probable questions being asked in the technical interviews, and their adequate answers and explanations.

This book gives not only the overall picture of SAP but also a good in-depth knowledge on the SAP-Production Planning Module. It also contains a detailed view of the potential questions as well as answers that you can expect in an interview related with SAP-PP. Moreover an attempt has been made to cover all the concepts related to Master data, MRP, demand management, SOP, and other important aspects of SAP PP. This book is equipped with Easy to understand language, practical examples, explanation of common issues and also with the answers to typical practical questions. It is highly recommended for learners and technical functional as well as techno-functional professionals.

About the Authors

The proficient team at Kogent Learning Solutions Inc. and Dreamtech Press has seized the market of computer books bringing excellent content in software development to the fore. The team is committed to excellence—excellence in quality of content, excellence in the dedication of its authors and editors, excellence in the attention to detail, and excellence in understanding the needs of its readers.

About Dreamtech Press

Dreamtech Press is one of the India’s leading IT, Management and Engineering books publisher, devoted to students and professionals, novices and experts, instructors and teachers. We have ardently analyzed and comprehended the needs of our readers. Moreover our meticulous care in creating and publishing our books; focusing on generic and specific educational requirements and demands of our readers makes us the best choice among readers. Efficacious process management and enduring quality processes have been hallmark towards our success.

Relationship Investing is the core of our business that has been the hallmark of our success. No wonder, respected global corporation – Apress/Springer, Manning Publication (USA), Source Books Inc., Career Press and W-Business have trusted our capability to deliver value in India. We have an exclusive sales and distribution tie-up with Wiley India Pvt. Ltd. wherein all the books printed by Dreamtech Press and distributed by Wiley India Pvt. Ltd.

Media Contact: Akash Kumar Cell: +91 987 383 8807 Email: akash.kumar@dreamtechpress.com

Filed Under: Book Review Tagged With: SAP

Top 10 JavaScript Tips for your site

February 24, 2011 by JavaBeat Leave a Comment

Introduction

A good looking site is always more preferable than a bland looking site with a boring layout. To jazz up any site, a developer uses JavaScript. It is a popular programming language that used in creating a website with interactive content & elements. The script is browser based and runs independently from page to page. Integrating java codes into a site is easy to create stunning looking websites. Here, you can find 10 scripts that are highly recommended for any website developer or designers.

1. No-Right Click Java Script

Right clicking is second nature to most web users. To avoid them from right clicking on your site, this javascript code can be used. It is mostly to avoid duplication of the information that is used on the site. Those who view the site, due to this code won’t be able to carry out even the normal functions like ‘copy & paste’, thus avoiding any possible data theft.

2. Counters

Google analytics is the best source to keep a track of visitors visiting the site. But, every time one wants to view the stats for their sites, they are required to log into their account, which is quite tedious. To make it easier in viewing the number of visitors a site can be installed with a ‘counter’ javascript. Having this javascript installed can enable the site to display the count for visitors frequenting the website. It is mostly useful for making constructive changes to render the site more traffic friendly.

3. World Time

Internet isn’t restricted to any particular time zone and that any website is accessible from anywhere in the world, it’s a good idea to have a world time clock displayed on the site. It is mostly to aid the visitors, and does little to attract traffic. This javascript is purely a visual element.

4. Animations

Those websites with fun animations are really great to look. Some sites are solely capable of attracting traffic on the basis of their use of interesting visual elements. So with the use of javascript to create fun & interesting apps or graphic for the site will surely boost the number of visitors on the site. What kind of animation to be used, solely depends on the developer and his preference.

5. Image Shuffle

Site that has lots and lots of images, it can get pretty confusing for the user to go through each them, and find the appropriate one. Using a script to constantly display a shuffling image is much better than the traditional thumbnail view and facilitates the use to use the site in much better way. The shuffling images also add an interesting effect to the entire layout of the site. This javascript is useful and also is very much helpful in increasing the ‘visually appealing’ quotient of a site.

6. Special Navigation

There is nothing more appealing on a site than a dedicated and easy to use navigation list or button. These are mostly drop down list, which contains categories or dates that can be used for browsing the content of the website. It is easy to install using javascript coding, and certain elements can be tweaked to render the navigation button/menu with some extra useful capabilities.

7. Colorful Scroll Bars

Making changes to color is one of the most common used in java scripting. It is done to add a personal touch to the entire layout using the color of choice. On most sites the scroll bar is usually grey. But, it can be changed to whatever color the user wishes to have, using java script. It adds a certain visual touch that makes the site appear attractive.

8. Bookmarks

Adding a site to your bookmark list is not a new thing. To extent the capabilities, one can integrate a better bookmarking tool, which can be used by the users who view the site. It will help them remember the page, without doing much search for the site the next time they want to visit the site.

9. Music Players

Create a versatile music player with the use of java script coding, and integrate it into the site so that people who like to listen to music, while browsing can find it useful. Any media player is interesting to look at and adding a media player to the site will jazz up the attractive factor that much more.

10. Password Protection

Password protecting a page isn’t recommended for most. But, for those few who do want to make their pages visible to only few, they can password protect it using a java code. With such pages, a user visiting the site won’t be able to view it, unless the person retains a proper password. Password protecting a page is huge turn off and should be used only when absolutely sure.

Filed Under: JavaScript

Static Code Analysis Tool – FireBugs

March 5, 2010 by JavaBeat Leave a Comment

What is FireBugs?

FindBugs is an open source program created by William Pugh which looks for bugs in Java code. It uses static analysis to identify hundreds of different potential types of errors in Java programs. FindBugs operates on Java bytecode,rather than source code. The software is distributed as a stand-alone GUI application. There are also plug-ins available for Eclipse, Netbeans, and IntelliJ IDEA

Official Website of FireBugs?

http://findbugs.sourceforge.net/

How to Install the Eclipse Plugin?

http://findbugs.cs.umd.edu/eclipse/

Demo & FAQ?

http://findbugs.sourceforge.net/demo.html / http://findbugs.sourceforge.net/FAQ.html

How does it work and how to use it?

a) After you install the eclipse plugin, restart eclipse.

b) Go to Window –> Show view –> other and select the find bug options available.

c) Open – perspective – Findbugs [Window –> open perspective–> findbugs]

c) Create a potential test class (with some obvious issues) like the following,

d) Initiate the find bugs by doing the following.

e) Now the errors get listed based on Project – Type – Package – Class – Priority – Category – Error – Location

f) Now you try to correct them

Filed Under: JavaScript Tagged With: FireBug

GWT user interface components

March 30, 2009 by JavaBeat Leave a Comment

HTML host page

A GWT module needs a HTML host page to run. The HTML page includes the GWT project through the script tag. In the HTML page we do not add any HTML code ourselves. It is the responsibility of the developer to programmatically include content into the HTML page through GWT. Lets look at a sample HTML host page :

1
2
3
4
5
6
7
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>Simple GWT Host Page</title>
    <script type="text/javascript" language="javascript" src="com.google.gwt.sample.tempraturewatch.TempratureWatch.nocache.js"></script>
 
 
 
<div id="tempratureWatchDiv"></div>

<meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>Simple GWT Host Page</title> <script type="text/javascript" language="javascript" src="com.google.gwt.sample.tempraturewatch.TempratureWatch.nocache.js"></script> <div id="tempratureWatchDiv"></div>

In the above host page we can see that the GWT application is included through the script tag. The nocache.js is an auto generated file created using the applicationcreator command (Refer : GWT installation and creating a GWT Project for information on the applicationcreator). Next, we can see a div tag with the id attribute.
In GWT we can insert content into selective sections of the HTML page. Lets look at an example :

1
2
final Button button = new Button("Submit");
RootPanel.get("tempratureWatchDiv").add(button);

final Button button = new Button("Submit"); RootPanel.get("tempratureWatchDiv").add(button);

In the above code snippet, we can see that usage of the class RootPanel. The RootPanel is the container for all other GWT components. We use the RootPanel class to get a reference of tempratureWatchDiv division. Once we have a reference to it we can add Widgets(controls) to the html page.

Widgets

Widgets are controls which allow the users to interact with the system. Lets look at the different types of widgets available in GWT:

  • Button
  • – Button enables the user to take a certain action

  • TextBox
  • – Textbox allows the user to enter data as text

  • Tree
  • – Tree represents a hierarchy of other widgets

  • RichTextArea
  • – RichTextArea provides the user to perform editing features on text

  • Checkbox
  • – Checkbox allows multiple selection of items

  • RadioButton
  • – RadioButton allows only single selection of items

  • PasswordTextBox
  • – PasswordTextBox is used to input password. The typed characters are not displayed as it is.

  • TextArea
  • – TextArea allows the user to enter text over multiple lines

  • Hyperlink
  • – Hyperlink allows you to link to an URL

  • Listbox
  • – Listbox allows multiple selection from a list of items

  • MenuBar
  • – MenuBar allows you to implement a standard menu bar. Menu bar can hold one or more menus.

  • SuggestBox
  • – SuggestBox is like a textbox but it provides suggestions based on the user input. The suggestions provided are pre-configured.

  • Table
  • – Table control mimics the HTML table

  • Dialog Box
  • – Dialog Box represents a form of popup

In addition to these we can also create custom widgets.

Panels

Panels are used as container for widgets and subpanels. Panels also define how the widgets will be laid out. Lets look at the type of panels in GWT:

  • Dock Panel
  • – Using dock panels the widgets are aligned directionally

  • Horizontal Panel
  • – Provides horizontal alignment of controls

  • Tab Panel
  • – Provides tabular arrangement of controls

  • Root Panel
  • – The Root panel holds the reference to the entire GWT interface.

  • Stack Panel
  • – The stack panel displays the components vertically by stacking its children.

  • Popup Panel
  • – The popup panel is a popup which can popup up over other widgets

  • Vertical Panel
  • – The vertical panel lays out the components in a vertical column

  • Flow Panel
  • – This panel lays out it components in the same manner as the default HTML layout

  • Vertical Split Panel
  • – This panels splits the window verticals into two widgets

  • Horizontal Split Panel
  • – This panels splits the window horizontally into two widgets

Style Sheets

In GWT we can apply style information to content by using Cascading Style Sheets (CSS). This is very similar to the way we apply style information to HTML pages. Each widget class in GWT has a addStyleName method which takes a string parameter. The string parameter associates a style name with the widget. The same name should be defined in the CSS file. Under the name we can set visual styling information. The reference to the CSS should be made in the GWT module. Let us now look at how we can make use of style sheets in a GWT application.

As a first step we have to associate the style attribute in the Java class:

1
2
Label nameLabel = new Label();
nameLabel.addStyleName("LabelStyle");

Label nameLabel = new Label(); nameLabel.addStyleName("LabelStyle");

The next step would be to define the style attribute in the CSS file:

1
2
3
4
.LabelStyle {
  color: blue;
  font-size: large;
}

.LabelStyle { color: blue; font-size: large; }

The final step would be to declare the style sheet file in the XML module. This enables the GWT to know exactly where to look for the styling information.

1
2
3
4
5
<module>
	<!--Other application level settings-->
	.......
	<stylesheet src="MyStyleSheet.css">
</stylesheet></module>

<module> <!--Other application level settings--> ....... <stylesheet src="MyStyleSheet.css"> </stylesheet></module>

GWT Reference

  • GWT installation and creating a GWT Project
  • GWT Articles

Filed Under: GWT Tagged With: GWT

GWT installation and creating a GWT Project

March 29, 2009 by JavaBeat Leave a Comment

Installing GWT

To develop programs using the GWT we need to first download it from here : GWT download.
Once you have it installed the next step would be to update the PATH environmental variable. For example if you have installed GWT in you C: drive as C:gwt-windows-1.5.3 then append this path to the end of the PATH variable. Once this is done you are ready to create GWT projects.

[Note: You need JDK 1.5 or above to develop GWT projects. You also need an IDE to develop the GWT projects. We will use Eclipse IDE in this tutorial]

Creating an Eclipse GWT project

Once the installation part is over we can now jump onto creating a new GWT project. Lets create a project which shows the temprature of cities.

  • Open windows command prompt and navigate to the GWT installation directory. For e.g: C:gwt-windows-1.5.3>
  • Create a directory by using the following command in current path:
    mkdir TempratureWatch
  • Change your current working directory to the directory we just created by using the following command:
    cd TempratureWatch

    After executing this command you should be at this location :

    C:gwt-windows-1.5.3TempratureWatch>
  • Next type the following command in the current path:
    projectCreator -eclipse TempratureWatch -out TempratureWatch
    

    After executing this command, a directory by the name TempratureWatch is created. Inside the directoty we see the following directory and files :

    • src – directory for storing the project source code
    • test – directory for storing unit testcase
    • .classpath – file used by Eclipse
    • .project – file used by Eclipse
  • Next execute the following command :

    applicationCreator -eclipse TempratureWatch -out TempratureWatch com.google.gwt.sample.tempraturewatch.client.TempratureWatch
    

    This command creates a package structure as specified in the command line and creates a java class called TempratureWatch.java which would be the application’s entry point. The package structure chosen is as per GWT naming conventions. The entry point class must always be inside the client directory. The command also create an XML document called TempratureWatch.gwt at this location com.google.gwt.sample.tempraturewatch. This file will hold configuration settings for the GWT application.

Importing the project to Eclipse

Once you have the project directories created by using the commands explained in the last section the next step would be import the project to Eclipse. This can be done by using the following steps :

  • Start Eclipse, then select File -> Import
  • Select the project root directory by selecting: General -> Existing Projects into Workspace
  • Select directory of the project. In our example we should choose: C:gwt-windows-1.5.3TempratureWatch
  • Click Finish

Once done, you should be able to see the imported project in the Eclipse workspace. To run the application in hosted mode select the project and select the Run option under the Run menu. If the program starts successfully then you should be able to see a sample page which is created by default when you create a GWT project.

Difference between Hosted mode and Web mode

There are two possible ways by which we can execute our GWT project:

  • Hosted mode
  • Web mode

The way we started our application in the last section was the Hosted mode execution. In hosted mode the application is converted to bytecode and executed by the JVM (very much like java). This allows us to take advantage of the Java language API. In addition to this the hosted mode also allows us to debug application easily.

In Web mode the code is converted to JavaScript and executed by the browser.

Filed Under: GWT Tagged With: GWT

SCJP 6.0 Certification – Rehearse It – Try It – Crack It with Dreamtech Press

December 2, 2008 by JavaBeat Leave a Comment

Dreamtech Press releases book that covers all the objectives of the Sun Java SCJP Exam 310-065. The book provides sample questions to build your confidence for the SCJP exam. ISBN: 978-81-7722-562-4 Price: RS. 429/- (2 Volume Set with CD)

Cracking the Sun certification exams is the most sought-after achievement for today’s IT students and professionals. It has been observed that in the fastest-growing IT world, the number of candidates appearing for the SCJP exam is also increasing leaps and bounds. Considering this fact, Dreamtech Press and Kogent solutions Inc. have once again joined hands to present a book that will assist both experienced Java professionals and those who are in the premature stage of gaining experience with Java technologies while appearing in Sun Certified Programmer for Java 6 SCJP (Exam 310-065) exam.

This book brings to you a detailed discussion on Java key concepts associated with the exam. This book not only provides the flavor of the SCJP 6.0 objectives but, an in-depth knowledge of the Java concepts mapped to these objectives. The sole objective of this book is to help Java programmers crack Sun Microsystem’s SCJP certification for Java 6.0. After reading this book thoroughly, the readers will feel boost up for the fact that they had recapped all the Sun Microsystem’s objectives laid down for the SCJP 6 exam.

Apart from the theoretical knowledge provided, this book is also coupled with Lab Manual + Question Bank, which offers you laboratory practices mapping the chapters in the study guide. Each lab contains 10 exercises and more than 1000 questions in total based on real-life scenarios. This supplement also provides you with the answers to the questions, with an explanation of the correct and incorrect options in a question.

Along with the Study guide and Lab Manual, this book comes with a CD containing a Ucertify prepkit with four complete SCJP mock exam papers, study notes and customized test, which should be tried before appearing for the exam. The accompanying CD also contains two mock exams in PDF format and additional questions based on exam objectives.

No doubt, this is a book, just what you need to transform your dream of achieving Sun certification into reality.

Ordering Information: ISBN: 978-81-7722-562-4 Price: RS. 429/- (2 Volume Set with CD) Enquiries: priyanka.batra@dreamtechpress.com

About the Company: The proficient team at Kogent Solutions Inc. and Dreamtech Press has seized the market of computer books bringing excellent content in software development to the fore. The team is committed to excellence – excellence in quality of content; excellence in the dedication of its authors and editors; excellence in the attention to detail; and excellence in understanding the needs of their readers.

Filed Under: Book Review Tagged With: SCJP 6.0 Book

Packt Publishing seeks authors for new Beginner’s Guide series

December 2, 2008 by JavaBeat Leave a Comment

PacktPub Press Release

Packt Publishing has today launched a new series of Beginner’s Guide books designed to make open source tools and other advanced software accessible and usable for Beginners.

“There are thousands of tremendous software tools out there,” says series editor David Barnes. “The way they are designed, built and documented means they can often feel like they are created by experts, for experts. Newcomers often don’t know what the software can even do, let alone how to do it.”

Packt Beginner’s Guides aim to overcome this problem. They teach newcomers a technology by presenting realistic, useful examples with clear step-by-step instructions.

Packt has already announced two Beginner’s Guides on their web site: Moodle Course Conversion, due out next week, and WordPress Plugin Development, due out in January.

“If you’re trying to teach a new application to somebody sitting next to you, you won’t just give them loads of facts about it” Barnes continued “Instead you’ll guide them through some simple, useful operations before explaining them and then gradually moving on to more complex tasks. Beginner’s Guides work like this. They feel more like a hands-on ‘lab’ than a lecture” he concluded.
Beginner’s Guides are especially suitable for tools that aren’t completely geeky, and aren’t completely mainstream either. Tools such as Alfresco, Moodle, WordPress, Joomla!, and Drupal all suit this kind of ‘learn by doing’ approach.
Beginner’s Guides take Packt’s approach a step further by providing friendly step-by-step books on topics and tools that are just starting to be adopted by mainstream users. Not long ago, if you used a computer for anything more than typing a letter, sending email and using Google you were considered an expert. But now anybody can use a computer in a wide range of creative and interesting ways – from building web sites to making videos and music. The need for friendly Beginner’s Guides on a wide range of topics and tools is greater than ever.

Packt is looking for authors to write books in the Beginner’s Guide series. “A good Beginner’s Guide author thinks like a teacher,” says David. “They need to be well versed and comfortable with the topic, so that while writing they can focus their attention on leading the reader into the topic area. We have plenty of editorial resources, templates, and guidelines that will help authors do just that.”
If you are well versed with the technology you want to write a book on and are keen to train new comers, you fit the bill. Good English skills are also a big help of course! If you are interested in writing these Beginner’s Guides please approach Packt at author@packtpub.com with the subject you want to cover, or some information on your areas of expertise.

About Packt

Packt is a modern, unique publishing company with a focus on producing cutting-edge books for communities of developers, administrators, and newbies alike. Packt believe in Open Source. When they sell a book written on an Open Source project, they pay a royalty directly to that project. As a result of purchasing one of our Open Source books, Packt will have given some of the money received to the Open Source project.

Filed Under: Book Review

How to solve QuerySyntaxException (table is not mapped) in hibetnate?

December 1, 2008 by JavaBeat Leave a Comment

The following exception is very common if you are the beginner for hibernate.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Exception in thread "main" org.hibernate.hql.ast.QuerySyntaxException: book is not mapped [from book]
	at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:158)
	at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:87)
	at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:70)
	at org.hibernate.hql.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:255)
	at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3056)
	at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:2945)
	at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:688)
	at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:544)
	at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:281)
	at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:229)
	at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:228)
	at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:160)
	at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:111)
	at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:77)
	at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:56)
	at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72)
	at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133)
	at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112)
	at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1623)
	at hibernate.HibernateExample.main(HibernateExample.java:15)

Exception in thread "main" org.hibernate.hql.ast.QuerySyntaxException: book is not mapped [from book] at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:158) at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:87) at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:70) at org.hibernate.hql.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:255) at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3056) at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:2945) at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:688) at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:544) at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:281) at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:229) at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:228) at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:160) at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:111) at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:77) at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:56) at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72) at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133) at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112) at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1623) at hibernate.HibernateExample.main(HibernateExample.java:15)

The above QuerySyntaxException is thrown when we are not mapping the table name properly. The first time hibernate users
can be seen this error because you will map the table name directly in the query. That will not work in the hibernate. You will have to
map the class name that is mapped in the Hibernate configuration file. Look into the following example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
 
/**
 * source : www.javabeat.net
 */
public class HibernateExample {
    public static void main(String args[]){
        Configuration configuration = new Configuration();
        SessionFactory  sessionFactory = configuration.configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        Query query = session.createQuery("delete from Book where id=5");
        query.executeUpdate();
        transaction.commit();
    }
}

package hibernate; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; /** * source : www.javabeat.net */ public class HibernateExample { public static void main(String args[]){ Configuration configuration = new Configuration(); SessionFactory sessionFactory = configuration.configure().buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); Query query = session.createQuery("delete from Book where id=5"); query.executeUpdate(); transaction.commit(); } }

In the above example Book is the class name that is mapped in the hbm file as follows:

Here the class names is case sensitive.

Filed Under: Hibernate Tagged With: hibernate query

Unit Testing with JUnit 4 Annotations

October 3, 2008 by JavaBeat Leave a Comment

JUnit 4.0 introduces a completely different API to the older versions. JUnit 4.0 uses Java 5.0 annotations to describe tests instead of using inheritence. It introduces more flexible initialization and cleanup, timeouts, and parameterized test cases. This post describes the new features in JUnit 4.0, and in the end, I show a basic example that tests the java.util.Stack class.

1. The tests

Unlike in JUnit 3.x you don’t have to extend TestCase to implement tests. A simple Java class can be used as a TestCase. The test methods have to be simply annotated with org.junit.Test annotation as shown below

[java]
@Test
public void emptyTest() {
stack = new Stack<String>();
assertTrue(stack.isEmpty());
}
[/java]

2. Using Assert Methods

In JUnit 4.0 test classes do not inherit from TestCase, as a result, the Assert methods are not available to the test classes. In order to use the Assert methods, you have to use either the prefixed syntax (Assert.assertEquals()) or, use a static importfor the Assert class.

[java]
import static org.junit.Assert.*;
[/java]

Now the assert methods may be used directly as done with the previous versions of JUnit.

3. Changes in Assert Methods

The new assertEquals methods use Autoboxing, and hence all the assertEquals(primitive, primitive) methods will be tested as assertEquals(Object, Object). This may lead to some interesting results. For example autoboxing will convert all numbers to the Integer class, so an Integer(10) may not be equal to Long(10). This has to be considered when writing tests for arithmetic methods. For example, the following Calc class and it’s corresponding test CalcTest will give you an error.

[java]
public class Calc {
public long add(int a, int b) {
return a+b;
}
}

import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class CalcTest {
@Test
public void testAdd() {
assertEquals(5, new Calc().add(2, 3));
}
}
[/java]

You will end up with the following error.

[java]
java.lang.AssertionError: expected:<5> but was:<5>
[/java]

This is due to autoboxing. By default all the integers are cast to Integer, but we were expecting long here. Hence the error. In order to overcome this problem, it is better if you type cast the first parameter in the assertEquals to the appropriate return type for the tested method as follows

[java]assertEquals((long)5, new Calc().add(2, 3));
[/java]

There are also a couple of methods for comparing Arrays

[java]
public static void assertEquals(String message, Object[] expecteds, Object[] actuals);
public static void assertEquals(Object[] expecteds, Object[] actuals);
[/java]

4. Setup and TearDown

You need not have to create setup and teardown methods for setup and teardown. The @Before, @After and @BeforeClass, @AfterClass annotations are used for implementing setup and teardown operations. The @Before and @BeforeClass methods are run before running the tests. The @After and @AfterClass methods are run after the tests are run. The only difference being that the @Before and @After can be used for multiple methods in a class, but the @BeforeClass and @AfterClass can be used only once per class.

5. Parameterized Tests

JUnit 4.0 comes with another special runner: Parameterized, which allows you to run the same test with different data. For example, in the the following peice of code will imply that the tests will run four times, with the parameter “number” changed each time to the value in the array.

[java]
@RunWith(value = Parameterized.class)
public class StackTest {
Stack<Integer> stack;
private int number;

public StackTest(int number) {
this.number = number;
}

@Parameters
public static Collection data() {
Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } };
return Arrays.asList(data);
}
…
}
[/java]

The requirement for parameterized tests is to
Have the annotation @RunWith for the Test Class
Have a public static method that returns a Collection for data. Each element of the collection must be an Array of the various paramters used for the test.
You will also need a public constructor that uses the parameters

6. Test Suites

In JUnit 3.8 you had to add a suite() method to your classes, to run all tests as a suite. With JUnit 4.0 you use annotations instead. To run the CalculatorTest and SquareTest you write an empty class with @RunWith and @Suiteannotations.

[java][/java]

 

[java]
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({StackTest.class})
public class AllTests {
}
[/java]

The “Suite” class takes SuiteClasses as argument which is a list of all the classes that can be run in the suite.

The following is a listing of the example StackTest used in the post.

[java]
package tests;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.Arrays;
import java.util.Collection;
import java.util.EmptyStackException;
import java.util.Stack;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(value = Parameterized.class)
public class StackTest {
Stack<Integer> stack;

private int number;

public StackTest(int number) {
this.number = number;
}

@Parameters
public static Collection data() {
Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } };
return Arrays.asList(data);
}

@Before
public void noSetup() {
stack = new Stack<Integer>();
}

@After
public void noTearDown() {
stack = null;
}

@Test
public void pushTest() {
stack.push(number);
assertEquals(stack.peek(), number);

}

@Test
public void popTest() {
}

@Test(expected = EmptyStackException.class)
public void peekTest() {
stack = new Stack<Integer>();
stack.peek();
}

@Test
public void emptyTest() {
stack = new Stack<Integer>();
assertTrue(stack.isEmpty());
}

@Test
public void searchTest() {
}
}
[/java]

If you are interested in receiving the future java articles and tips from us, please subscribe here. If you have any doubts on JUnit, please post it in the comments section. If you are working on the JUnit testing environment and looking for any example code, please post it in the comments section. We will come up with the sample code to help you. If you want to share your experience on the JUnit, please write it on the comments section.

  • Testing Support in Spring Framework

Filed Under: Testing Tagged With: JUNit, JUnit 4.0, Unit Testing

  • 1
  • 2
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved