I need to read messages_hr.properties file that is in the classpath of web project.
1) Load properties file:
ResourceBundle bridgeMsgBundle = ResourceBundle.getBundle("messages", new Locale("hr"));
2) Fomat text with parameters:
String text = MessageFormat.format(bridgeMsgBundle.getString("javax.faces.validator.LengthValidator.MAXIMUM"), 15);
In messages_hr.properties:
javax.faces.validator.LengthValidator.MAXIMUM=* Maksimalan broj znakova je {0}.
Monday, April 23, 2012
Wednesday, January 11, 2012
Using java formatter on web
HTML will eat spaces.. use  
To get rightly aligned columns you need to use font that is monospaced!
To get rightly aligned columns you need to use font that is monospaced!
Formatter formatter = null;
StringBuilder sb = new StringBuilder();
sb.append("%-").append(max).append(".").append(max).append("s");
String format = sb.toString();
for (Article a : listaArtikala)
{
// html pojede razmake - moras koristiti   i monospaced font (npr Courier)
sb = new StringBuilder();
formatter = new Formatter(sb);
formatter.format(format, a.getName() + ",");
formatter.format("%-14.14s", a.getArticlePeriod().getFormatted() + ",");
formatter.format("%-10.10s", CurrencyUtils.formatCurrency(a.getPrice()) + "kn");
if (log.isDebugEnabled()) log.debug(formatter.toString());
articleTypeSIList.add(new SelectItem(a.getOid(), formatter.toString().replace(" ", " ")));
}
Sort by 2 properties
There is list of articles that needs to be sorted by zone and then by name
List<Article> listaArtikala = articleManager.findByFilter(filter);
// sortiraj artikle po zoni
Collections.sort(listaArtikala, new Comparator<Article>()
{
@Override
public int compare(Article o1, Article o2)
{
return o1.getZone().getMark().compareTo(o2.getZone().getMark());
}
});
// razdvoji po zoni aktikle
Map<String, List<Article>> map = new TreeMap<String, List<Article>>();
for (Article a : listaArtikala)
{
String mark = a.getZone().getMark();
List<Article> tempList = map.get(mark);
if (tempList == null)
{
tempList = new ArrayList<Article>();
map.put(mark, tempList);
}
tempList.add(a);
}
listaArtikala.clear();
// sortiraj po imenu artikla
for (String mark : map.keySet())
{
List<Article> tempList = map.get(mark);
Collections.sort(tempList, new Comparator<Article>()
{
@Override
public int compare(Article o1, Article o2)
{
return o1.getName().compareTo(o2.getName());
}
});
listaArtikala.addAll(tempList);
}
Thursday, January 5, 2012
Reading Active Directory
Example of reading users e-mail address from AD:
public static void main(String[] args)
{
Hashtable env = new Hashtable(11);
env.put(Context.SECURITY_PRINCIPAL, "userName (CN)");
env.put(Context.SECURITY_CREDENTIALS, "pass");
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://serverName:389/DC=domain1,DC=hr");
String users = "ou=Unit,ou=Organizational";
try
{
DirContext ctx = new InitialDirContext(env);
Attributes answer = null;
String[] attrIDs = { "mail" };//Specify the ids of the attributes to return
NamingEnumeration list = ctx.list(users);
while (list.hasMore())
{
NameClassPair nc = (NameClassPair) list.next();
System.out.println(nc.getName());
answer = ctx.getAttributes(nc.getName() + " , " + users, attrIDs);
for (NamingEnumeration ae = answer.getAll(); ae.hasMore();)
{
Attribute attr = (Attribute) ae.next();
System.out.println("attribute: " + attr.getID());
/* Print each value */
for (NamingEnumeration e = attr.getAll(); e.hasMore(); System.out.println(e.next()))
;
}
}
}
catch (NamingException e)
{
System.err.println(e);
}
}
Resources:
http://www.windowsnetworking.com/kbase/WindowsTips/Windows2000/AdminTips/ActiveDirectory/ActiveDirectoryNamingStandard.html
http://docs.oracle.com/javase/tutorial/jndi/ops/getattrs.html
Wednesday, January 4, 2012
Primefaces and encoding (UTF-8)
From pom.xml
With Sun implementations special chars (šđčćž) are transformed to unreadable chars!!!
It works well with Apache implementation:
The index.xhtml page:
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>3.0</version>
</dependency>
With Sun implementations special chars (šđčćž) are transformed to unreadable chars!!!
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.6</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.6</version>
</dependency>
It works well with Apache implementation:
<dependency>
<groupId>org.apache.myfaces.core</groupId>
<artifactId>myfaces-api</artifactId>
<version>2.1.5</version>
</dependency>
<dependency>
<groupId>org.apache.myfaces.core</groupId>
<artifactId>myfaces-impl</artifactId>
<version>2.1.5</version>
</dependency>
The index.xhtml page:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<f:view contentType="text/html">
<h:head>
</h:head>
<h:body>
<h:form>
<h1>TESTING JSF and PRIMEFACES</h1>
<h:panelGrid columns="3">
<h:outputLabel for="lastName" value="Name: " />
<h:inputText id="lastName" value="#{userInputBean.name}"/>
<h:message for="lastName" styleClass="error" />
</h:panelGrid>
<br />
<h:outputText value="#{userInputBean.name}" />
<p:editor />
</h:form>
</h:body>
</f:view>
</html>
Wednesday, December 21, 2011
Dynamically load header message in column
In backing bean I have List vrsteAktivnosti and based on kratica property in my object I want to build header so it can easily be internationalized. Plus add sufix '_kratica' to property.
If for example kratica resolves to KR in my resource bundle I have key KR_kratica.
Some expression language basics:
If for example kratica resolves to KR in my resource bundle I have key KR_kratica.
<ui:param name="kratica_3" value="#{aktivnostBean.vrsteAktivnosti.get(3).kratica}_kratica" />
<p:column headerText="#{msg[kratica_3]}">
...
Some expression language basics:
- msg.someKey will look at message bundle for someKey
- msg['someKey'] will look at message bundle for someKey
- msg[someKey] will look at params to resolve property someKey
- msg[aktivnostBean.vrsteAktivnosti.get(3).kratica] will look at objects property kratica and then look at msg bundle
- msg[aktivnostBean.vrsteAktivnosti.get(3).kratica_kratica] will look at objects property kratica_kratica which does not exist, so use ui:param
Tuesday, December 13, 2011
Eclipse preferences
- Hot deploy on Tomcat - when you make changes to class it should be asap visible in Tomcat (JRebel would like that :)
- Create Launch Configuration under Tomcat - Launch (Preferences), Debug is checked
- This is working only on web project, not projects included in it
- General - check Show heap status
- General - Workspace - set Text file encoding
- General - Editors- Text Editors - Show line nubers
- Run/Debug - Console - uncheck Limit console output
- modify start shortcut:
- "C:\MyEclipse\myeclipseforspring.exe" -data D:\Workspace\Play -vmargs -Xmx768m -XX:MaxPermSize=384m -XX:ReservedCodeCacheSize=64m
- add latest Subclipse
- add bin and target folders to global svn ignore list
- Windows - Preferences - Team - Ignored Resources - Add Pattern
- enter bin then target then m2-target
- remove antivirus scan from workspace and eclipse installation directory
- add -showlocation as first line in eclipse.ini to show workspace location in title bar
Find resource in specific folder?
Open resource (Ctrl + Shift + R) - find start.jsp in msgbox subfolder:
*/msgbox/start.jsp
How to tell eclipse where is my java located?
Edit eclipse.ini file add line before -vmargs:
-vm (new line needed :)
C:\Java\jdk1.6.0\jre\bin\javaw.exe
How to change @author default field in Javadoc?
Edit eclipse.ini file, add line
-Duser.name=My name
Missing deployment assembly even if Dynamic Web Module is added as project facet
Add
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
to your .project file.
Quick Search
CTRL+SHIFT+L
https://marketplace.eclipse.org/content/quick-search-eclipse
https://spring.io/blog/2013/07/11/eclipse-quick-search/
Add decompiler
http://jadclipse.sourceforge.net/wiki/index.php/Main_Page
http://www.mkyong.com/java/java-decompiler-plugin-for-eclipse/
Ref:
http://wiki.eclipse.org/Eclipse.ini
What are the best JVM settings for Eclipse?
https://dzone.com/articles/show-workspace-location-title
TOMCAT - JVM parameters:
Open resource (Ctrl + Shift + R) - find start.jsp in msgbox subfolder:
*/msgbox/start.jsp
How to tell eclipse where is my java located?
Edit eclipse.ini file add line before -vmargs:
-vm (new line needed :)
C:\Java\jdk1.6.0\jre\bin\javaw.exe
How to change @author default field in Javadoc?
Edit eclipse.ini file, add line
-Duser.name=My name
Missing deployment assembly even if Dynamic Web Module is added as project facet
Add
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
to your .project file.
Quick Search
CTRL+SHIFT+L
https://marketplace.eclipse.org/content/quick-search-eclipse
https://spring.io/blog/2013/07/11/eclipse-quick-search/
Add decompiler
http://jadclipse.sourceforge.net/wiki/index.php/Main_Page
http://www.mkyong.com/java/java-decompiler-plugin-for-eclipse/
Ref:
http://wiki.eclipse.org/Eclipse.ini
What are the best JVM settings for Eclipse?
https://dzone.com/articles/show-workspace-location-title
TOMCAT - JVM parameters:
-Xms256m -Xmx1024m
-XX:PermSize=64m -XX:MaxPermSize=512m
-Dorg.apache.el.parser.COERCE_TO_ZERO=false
-Dsun.jnu.encoding=UTF-8
-Dfile.encoding=UTF-8
JVM params explained
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-XX:PermSize<size> set initial PermGen Size
-XX:MaxPermSize<size> set the maximum PermGen Size
https://www.mkyong.com/java/find-out-your-java-heap-memory-size/
JVM params explained
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-XX:PermSize<size> set initial PermGen Size
-XX:MaxPermSize<size> set the maximum PermGen Size
https://www.mkyong.com/java/find-out-your-java-heap-memory-size/
Thursday, November 17, 2011
Stubs vs Mocks
A stub is a piece of code that’s inserted at runtime in place of the real code, in order to isolate the caller from the real implementation. The intent is to replace a complex behavior with a simpler one that allows independent testing of some part of the real code.
Mocks replace real objects from the inside, without the calling classes being aware of it; They are objects pre-programmed with expectations which form a specification of the calls they are expected to receive.
The most important point to consider when writing a mock is that it shouldn’t have any business logic. It must be a dumb object that does only what the test tells it to do. It’s driven purely by the tests. This characteristic is exactly the opposite of stubs, which contain all the logic.
http://martinfowler.com/articles/mocksArentStubs.html
Monday, November 14, 2011
Aspect Oriented Programming (AOP)
Enables modularization of cross-cutting concerns (to avoid tangling and to eliminate scattering)
2. Join Point - places within your code that are eligible for advice; method execution
3. Pointcut - description of the joinpoint you want to advise; you list the criteria of the joinpoint you are interested in advising here. Eg.
4. Aspect - functionality you actually want to add to an object (e.g. logging, security)
Aspects use Pointcuts to find Joinpoints to give Advice to ...
Aspects have APIs which aim to solve a common problem, like logging, and exception handling.
These are then invoked while intercepting the actual method invocation. Such APIs are termed Advice.
Advices are interceptors, which intercept original method invocation and wrap it around with handling of cross cutting concerns.
Now, for applying Advices to methods, AOP provides artifacts named JoinPoint.
Using a JoinPoint we could defne, which API invocation would be wrapped around by what Advice.
Weaving is a mechanism by which the aspects are applied to the designated classes and methods.
Weaving is generally done by generating byte code for the interceptors, using various libraries for byte code generation libraries, such as JavaAssist, BCEL, and ASM.
There are three places, any of which could be used to generate the bytecode. These are while compiling the code (Compile Time Weaving), loading the application known as (Load Time Weaving) and (Runtime Time Weaving) while actual method invocation is running.
Ref:
Spring doc
Learning Google Guice
Concepts:
1. Advice - The actual work AOP will perform on a given object (around, before, after)2. Join Point - places within your code that are eligible for advice; method execution
3. Pointcut - description of the joinpoint you want to advise; you list the criteria of the joinpoint you are interested in advising here. Eg.
execution(public * *(..))4. Aspect - functionality you actually want to add to an object (e.g. logging, security)
Aspects use Pointcuts to find Joinpoints to give Advice to ...
How AOP works?
AOP works by separating common concerns across the layers in separate classes and names them Aspect.Aspects have APIs which aim to solve a common problem, like logging, and exception handling.
These are then invoked while intercepting the actual method invocation. Such APIs are termed Advice.
Advices are interceptors, which intercept original method invocation and wrap it around with handling of cross cutting concerns.
Now, for applying Advices to methods, AOP provides artifacts named JoinPoint.
Using a JoinPoint we could defne, which API invocation would be wrapped around by what Advice.
Weaving is a mechanism by which the aspects are applied to the designated classes and methods.
Weaving is generally done by generating byte code for the interceptors, using various libraries for byte code generation libraries, such as JavaAssist, BCEL, and ASM.
There are three places, any of which could be used to generate the bytecode. These are while compiling the code (Compile Time Weaving), loading the application known as (Load Time Weaving) and (Runtime Time Weaving) while actual method invocation is running.
Ref:
Spring doc
Learning Google Guice
Tuesday, November 8, 2011
Clearing JSF Form
On page you have form with input fields and button that can clear that fields.
Button is set to immediate since there is no need to do PROCESS_VALIDATIONS and UPDATE_MODEL_VALUES phases,
instead method is invoked in APPLY_REQUEST_VALUES phase.
First method can be used in JSF 1.x or 2.x, but second is based on AJAX event and is usable only in JSF 2.x
Better approach is with AJAX since there is no need to refresh whole page.
Button is set to immediate since there is no need to do PROCESS_VALIDATIONS and UPDATE_MODEL_VALUES phases,
instead method is invoked in APPLY_REQUEST_VALUES phase.
First method can be used in JSF 1.x or 2.x, but second is based on AJAX event and is usable only in JSF 2.x
Better approach is with AJAX since there is no need to refresh whole page.
<h:commandButton value="Clear" id="clearButton">
<f:ajax event="click" render="@form" listener="#{myController.clearForm}" immediate="true" />
</h:commandButton>
public void clearForm(ActionEvent ae)
{
System.out.println("clearForm - via ActionEvent");
// clear bean values ...
// clear component values
UIComponent form = getContainingForm(ae.getComponent());
clearEditableValueHolders(form);
}
public void clearForm(AjaxBehaviorEvent ae)
{
System.out.println("clearForm - via AjaxBehaviorEvent");
// clear bean values ...
// clear component values
UIComponent form = getContainingForm(ae.getComponent());
clearEditableValueHolders(form);
}
private UIComponent getContainingForm(UIComponent component)
{
if (!(component.getParent() instanceof UIForm))
{
return getContainingForm(component.getParent());
}
else
{
System.out.println("getContainingForm: UIForm found");
return component.getParent();
}
}
private void clearEditableValueHolders(UIComponent form)
{
Iterator<UIComponent> iterator = form.getFacetsAndChildren();
while (iterator.hasNext())
{
UIComponent c = iterator.next();
if (c instanceof EditableValueHolder)
{
// Convenience method to reset this component's value to the un-initialized state.
((EditableValueHolder) c).resetValue();
}
clearEditableValueHolders(c);
}
}
Wednesday, October 26, 2011
Hibernate LazyInitializationException handling
In toString() method you want to output objects that are lazy fetched.
Solution that I use is via reflection with exception catching.
This will work only for fields declared in this class not super!
Solution that I use is via reflection with exception catching.
This will work only for fields declared in this class not super!
@Override:
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append(......);
sb.append(ExceptionHandler.ignoreLazy(this, "zone"));
return sb.toString();
}
public class ExceptionHandler:
public static String ignoreLazy(Object whom, String property)
{
try
{
Field field = whom.getClass().getDeclaredField(property);
field.setAccessible(true);
Object print = field.get(tkoMeSadrzi);
return print.toString();
}
catch (NoSuchFieldException e)
{
log.warn("DEVELOPER EXC ", e);
return "NoSuchFieldException: " + e.getMessage();
}
catch (Exception lazy)
{ //ignore
//log.debug("******* IGNORE LAZY : "+property);
return "lazy loaded!";
}
}
Hibernate show sql with parameters
#log hibernate prepared statements/SQL queries
#(equivalent to setting 'hibernate.show_sql' to 'true')
log4j.logger.org.hibernate.SQL=debug
# log JDBC bind parameter runtime arguments
log4j.logger.org.hibernate.type=trace
To format sql output put this line in hibernate configuration file:
hibernate.format_sql
Wednesday, September 21, 2011
Calling procedure using SQL
In my case procedure does not need to return anything.
Calling it from DAO layer:
Calling it from DAO layer:
String queryString = "call myProcedure()";
Query query = getSession().createSQLQuery(queryString);
query.executeUpdate();
Thursday, September 15, 2011
Associations via criteria
Fetch data from one table by criteria on linked table
Person has Address. (1:1)Address has field street.
I want to fetch all Persons that has Address with with specific street.
DetachedCriteria criteria= DetachedCriteria.forClass(Person.class);
criteria.createCriteria("address").add(Restrictions.eq("street", "WANTED"));
SELECT * FROM PERSON p inner join ADDRESS a on p.addressID=a.ID WHERE a.street=?Fetch data from one table by having foreign key of linked table
Object A has 1:1 relation to object B.Table A has foreign key to table B.
Class A has B.
I want to fetch class A and I only have ID of class B.
How to construct criteria?
SELECT * FROM a WHERE b_ID=?
//createCriteria on class A
criteria.add(Restrictions.eq("b.id", b.getId()));
criteria.list();
Fetch data from 3 linked tables
DPT has 1:n relation to OFFCOURTPAYMENT,OFFCOURTPAYMENT has 1:n relation to SUBJECTASSEMBLY
How to fetch DPTs that belong to specific SUBJECTASSEMBLY?
select d.* from DPT d
INNER JOIN OFFCOURTPAYMENT o ON D.ACTIVEOCPOID = O.OID
INNER JOIN SUBJECTASSEMBLY sa ON SA.OID = O.SUBJECTASSEMBLYOID
where d.COMPANYOID= coid (4)
and D.CURRENTSTATE = 'MIROVANJE'
and SA.RECORDNUMBER = '1'
and SA.SUBJECTABLETYPE = 'OCS_DPT'
SubjectAssembly sa is passed in method
DetachedCriteria crit = DetachedCriteria.forClass(DailyParkingTicket.class);
crit.add(Restrictions.eq("currentDPTState", DPTState.StateName.MIROVANJE));
DetachedCriteria saCrit = crit.createCriteria("activeOcp").createCriteria("subjectAssembly"); // 2 inner joins will be generated
saCrit.add(Restrictions.eq("recordNumber", sa.getRecordNumber()));
saCrit.add(Restrictions.eq("subjectableType", sa.getSubjectableType()));
criteria.getExecutableCriteria(getSession()).list();
Notes
I want to fetch (via join) objects associated with my source object A:A has list of Bs and B has C.
DetachedCriteria criteria= DetachedCriteria.forClass(A.class);
criteria.setFetchMode("B", FetchMode.JOIN); //must be present!
criteria.setFetchMode("B.C", FetchMode.JOIN);
// without DISTINCT_ROOT_ENTITY @ManyToMany returns full cartesian join!criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
Wednesday, September 14, 2011
@Column annotation and constraints in db
@Column(unique = true, nullable = false)
private Date startDate;
This annotation is description on startDate column when reading java file.
It is not used to stop inserting or updating database with false values, if you do not have constraints on table!
It can be used for generating table from entity class.
1 exception to the above rule:
If you try insert null into not null field declared in annotation it will throw Exception!
Friday, August 26, 2011
Open file with default program
In my example I have pdf file that I want to be opened as soon as it is saved to disk.
public static void openFile(File fileObj)
{
    StringBuilder sb = new StringBuilder();
    sb.append("cmd.exe /C start ");
    sb.append(fileObj.getAbsolutePath());
    System.out.println("openFile: " + sb);
    try
    {
        Runtime.getRuntime().exec(sb.toString());
    }
    catch (IOException e)
    {
        System.out.println("EEExxxccc");
    }
    }
Tuesday, August 23, 2011
Hibernate -distinct (with disjunction) via criteria
How to write distinct using Hibernate criteria API?
DetachedCriteria crit = DetachedCriteria.forClass(clazz);
Disjunction dis = Restrictions.disjunction(); // OR
dis.add(Restrictions.eq("billType", BillType.RACUN));
dis.add(Restrictions.eq("billType", BillType.STORNO));
crit.add(dis);
crit.setProjection(Projections.distinct(Projections.property("billSubtype")));
Criteria criteria = crit.getExecutableCriteria(getSession());
return crit.list();
select distinct B.BILLSUBTYPE from bill b where (B.BILLTYPE = 'RACUN' or B.BILLTYPE = 'STORNO')
http://www.jairrillo.com/blog/2009/01/29/how-to-use-left-join-in-hibernate-criteria/
Friday, July 22, 2011
Web -parameter transmission
(from jsf page to bean)
.xhtml:
<h:commandLink value="clickToTransfer" actionListener="#{activeBackingBean.methodName}" title="Hover effect">
<f:param name="myParam" value="TakeMe" />
</h:commandLink>
.java:
String parametar = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("myParam");
Ref:
4-ways-to-pass-parameter-from-jsf-page-to-backing-bean
Friday, July 15, 2011
Spring autowired behaviour
2 classes implement the same interface, 2 beans defined in configuration file for 2 different implementations.
eg. I have 2 beans of the same interface BillManager.
eg. I have 2 beans of the same interface BillManager.
@Autowired
BillManager manager;
org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type...
solution:
import org.springframework.beans.factory.annotation.Qualifier;
@Autowired
@Qualifier(value = "billManagerImpl_1") //write bean ID or name
BillManager manager;
Thursday, July 14, 2011
Hibernate - SQL Query
This post is written while using Hibernate 3.x version
Generated SQL:
When using helper entity (that is not persisted) when data is fetched from many tables you can use ResultTransformer:
How to map enum field?
import org.hibernate.impl.TypeLocatorImpl;
import org.hibernate.type.Type;
import org.hibernate.type.TypeResolver;
import org.hibernate.type.EnumType;
import org.hibernate.type.LongType;
Properties pmParams = new Properties();
pmParams.put("enumClass", "hr.samara.model.PaymentMethod");
pmParams.put("type", "12"); /* EnumType.STRING type = 12 */
Type pmType = new TypeLocatorImpl(new TypeResolver()).custom(EnumType.class, pmParams);
I removed default setter and made custom - bad :(
Ref:
http://www.journaldev.com/3422/hibernate-native-sql-example-addscalar-addentity-addjoin-parameter-example
https://stackoverflow.com/questions/9633337/hibernate-sql-transformation-fails-for-enum-field-type
String sqlQuery =
"select max(to_number(POLJE)) from TABLICA where COMPANYID=:company ";
SQLQuery query = getSession().createSQLQuery(sqlQuery);
query.setParameter("company", 1008);
query.addScalar("max(to_number(POLJE))", Hibernate.LONG); //in db it is varchar// you need to use StandardBasicTypes.LONG) in Hibernate v 4.3.xLong l = (Long) query.uniqueResult();if (l == null) return 0L;else return lL;
//if result is empty result set.. returned value will be nullGenerated SQL:
select
max(to_number(POLJE))
from
TABLICA
WHERE
COMPANYID=?
When using helper entity (that is not persisted) when data is fetched from many tables you can use ResultTransformer:
select B.BILLNUMBERPREFIX || B.BILLNUMBER AS billNumber, T.CREDIT, T.EVENTDATE ....
query.addScalar("billNumber").addScalar("credit", LongType.INSTANCE).addScalar("eventDate");
//necessary because property CREDIT is not the same as credit in Java (case sensitivity!)
query.setResultTransformer(Transformers.aliasToBean(MyHelperClass.class));
log.info("\n\nSQL: " + query.getQueryString() + "\n\n");
How to map enum field?
import org.hibernate.impl.TypeLocatorImpl;
import org.hibernate.type.Type;
import org.hibernate.type.TypeResolver;
import org.hibernate.type.EnumType;
import org.hibernate.type.LongType;
Properties pmParams = new Properties();
pmParams.put("enumClass", "hr.samara.model.PaymentMethod");
pmParams.put("type", "12"); /* EnumType.STRING type = 12 */
Type pmType = new TypeLocatorImpl(new TypeResolver()).custom(EnumType.class, pmParams);
I removed default setter and made custom - bad :(
public void setSmsState(String smsState)
{
this.smsState = SmsState.valueOf(smsState);
}
Ref:
http://www.journaldev.com/3422/hibernate-native-sql-example-addscalar-addentity-addjoin-parameter-example
https://stackoverflow.com/questions/9633337/hibernate-sql-transformation-fails-for-enum-field-type
Subscribe to:
Posts (Atom)