Default value in HIBERNATE Database independently

How to initialize Field in Hibernate @Entity without using @Column( columnDefenition=”” ) ?
WHY?
Because columnDefinition is DB dependently option.

Imagine you have some @Entity :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    @Column( name = "insstmp", nullable = false )
    @Type( type = "org.joda.time.contrib.hibernate.PersistentDateTime" )
    private DateTime insstmp;// date without time

    @Column( name = "updstmp", nullable = false )
    @Type( type = "org.joda.time.contrib.hibernate.PersistentDateTime" )
    private DateTime updstmp;// date without time

    /**
     * We set default value in case if the value is not set yet.
     */

    @PrePersist
    public void prePersist() {

        if ( this.updstmp == null ) {
            // Default value
            this.updstmp = getUpdstmp();
        }
        if ( this.insstmp == null ) {
            // Default value
            this.insstmp = getInsstmp();
        }
    }


    /**
     * Getter.
     *
     * @return the insstmp
     */

    public final DateTime getInsstmp() {

        return insstmp == null ? new DateTime( DateTimeZone.UTC ) : insstmp;
    }

    /**
     * Getter.
     *
     * @return the updstmp
     */

    public final DateTime getUpdstmp() {

        return updstmp == null ? new DateTime( DateTimeZone.UTC ) : updstmp;
    }

Java Interview questions and Tests

[2016-12-21]

Bank @A@

  • Do you know PL/SQL
  • What Do you preffer SPRING of JEE ?
  1. Privitive types in Java. Where is located variables of primitive types ?
    http://www.quizful.net/interview/java/java-local-variables

    Если вы создаете и присваиваете локальную переменную примитивного типа, то все данные полностью хранятся на стеке. Если же вы создаете объект, то ссылка хранится на стеке, сам же объект уже создается в куче. При создании массива примитивных типов происходит то же самое что и с объектами: ссылка на массив храниться на стеке, а сам массив в куче.Однако начиная с Java 6 Update 14 можно включить так называемый Escape-Analysis, который будет размещать объекты не покидающие метода тоже на стеке. Сделать это можно выставив параметр -XX:+DoEscapeAnalysis. Но он будет работать только в -server моде. В Java 6 Update 18 данную опцию отключили, а в Java 6 Update 21 вернули и сделали по умолчанию. Таким образом в вашей JVM запущенной на сервере данная оптимизация уже работает, если вы используете java6u21 и выше.
    Размещение объектов и примитивов на стеке несказанно упрощает жизнь сборщику мусора. Пользуйтесь этим - создавайте небольшие маложивущие immutable объекты вместо часто изменяемых долгоживущих
  2. JPA. There is stateless beans and statefull – what is difference ?
  3. JSF. What is living circle of JSF ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Your task is to make sure that this mapper code does not fail on corrupt data lines,
# but instead just ignores them and continues working
import sys

def mapper():
    # read standard input line by line
    for line in sys.stdin:
        # strip off extra whitespace, split on tab and put the data in an array
        data = line.strip().split("\t")

        # This is the place you need to do some defensive programming
        # what if there are not exactly 6 fields in that line?
        # YOUR CODE HERE
        if len(data)==6 :
       
            # this next line is called 'multiple assignment' in Python
            # this is not really necessary, we could access the data
            # with data[2] and data[5], but we do this for conveniency
            # and to make the code easier to read
            date, time, store, item, cost, payment = data
       
            # Now print out the data that will be passed to the reducer
            print "{0}\t{1}".format(store, cost)
       
       
test_text = """2013-10-09\t13:22\tMiami\tBoots\t99.95\tVisa
2013-10-09\t13:22\tNew York\tDVD\t9.50\tMasterCard
2013-10-09 13:22:59 I/O Error
^d8x28orz28zoijzu1z1zp1OHH3du3ixwcz114<f
1\t2\t3"""


# This function allows you to test the mapper with the provided test string
def main():
    import StringIO
    sys.stdin = StringIO.StringIO(test_text)
    mapper()
    sys.stdin = sys.__stdin__

Java String Anagrams

Problem
Two strings and are called anagrams if they consist same characters, but may be in different orders. So the list of anagrams of is .

Given two strings, print Anagrams if they are anagrams, print Not Anagrams if they are not. The strings may consist at most English characters; the comparison should NOT be case sensitive.

This exercise will verify that you can sort the characters of a string, or compare frequencies of characters.

Sample Input 0

anagram
margana

Sample Output 0

Anagrams

Sample Input 1

anagramm
marganaa
Sample Output 1:

Not Anagrams

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
    /**
     * Two strings and are called anagrams if they consist same characters, but may be in different orders. So
     * the list of anagrams of is .
     *
     * Given two strings, print Anagrams if they are anagrams, print Not Anagrams if they are not. The strings
     * may consist at most English characters; the comparison should NOT be case sensitive.
     *
     * This exercise will verify that you can sort the characters of a string, or compare frequencies of
     * characters.
     *
     * @param a
     * @param b
     *
     * @return
     */

    static boolean isAnagram( String a, String b ) {

        Collection<String> s1 = new ArrayList<>();

        for (int i = 0; i < a.length(); i++) {
            s1.add( String.valueOf( a.charAt( i ) ).toUpperCase() );
        }

        boolean result = true;
        for (int i = 0; i < b.length(); i++) {
            String charAt = String.valueOf( b.charAt( i ) ).toUpperCase();
            if ( !s1.contains( charAt ) ) {
                result = false;
            } else {
                s1.remove( charAt );
                //System.out.print( charAt + " : " );
                //System.out.println( s1 );
            }
        }

        return s1.size() > 0 ? false : result;
    }

Java String Compare

Problem
Given a string, find out the lexicographically smallest and largest substring of length .

[Note: Lexicographic order is also known as alphabetic order dictionary order. So “ball” is smaller than “cat”, “dog” is smaller than “dorm”. Capital letter always comes before smaller letter, so “Happy” is smaller than “happy” and “Zoo” is smaller than “ball”.]

Input Format

First line will consist a string containing english alphabets which has at most characters. 2nd line will consist an integer .

Output Format

In the first line print the lexicographically minimum substring. In the second line print the lexicographically maximum substring.

Sample Input

1
2
welcometojava
3

Sample Output

1
2
ava
wel

Explanation

Here is the list of all substrings of length :

1
2
3
4
5
6
7
8
9
10
11
wel
elc
lco
com
ome
met
eto
toj
oja
jav
ava

Among them ava is the smallest and wel is the largest.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
 * Copyright 2016. ABN Software. All Rights reserved.<br>
 * <br>
 * Created ..... 3 окт. 2016 г.<br>
 * <br>
 */

package info.abnsoft.java.HackerRank.sep2016;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

/**
 * @author annik
 *
 */

public class SolutionStringLexi {

    public static void main( String[] args ) {

        /*
         * Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named
         * Solution.
         */

        Scanner sc = new Scanner( System.in );
        String str = sc.nextLine();
        int count = sc.nextInt();
        sc.close();
//        System.out.println(str);
//        System.out.println(count);
        // splitted words :
        List<String> splitted = new ArrayList<String>();
        // sorted words
        List<String> result = new LinkedList<String>();
        if ( str.length() <= count ) {
            result.add( str );
        } else {
            for (int i = 0; i <= str.length() - count; i++) {
                //            System.out.println(str.substring(i,i+count));
                splitted.add( str.substring( i, i + count ) );
            }
            String cur = splitted.get( 0 );
            result.add( cur ); // add 1st element

            System.out.println( splitted );

            // TODO : if size==0 ?
            for (int i = 1; i < splitted.size(); i++) {
                boolean notFoundMin = true;
                for (int j = 0; j < result.size(); j++) {
                    cur = result.get( j );
                    if ( isLexicSmaller( splitted.get( i ), cur ) ) {
                        // when arr[i] is smaller insert at first
                        result.add( j, splitted.get( i ) );
                        notFoundMin = false;
//                        cur = splitted.get( i );
                        break;
                    }
                }
                if ( notFoundMin ) {
                    result.add( splitted.get( i ) ); // add at the end of list
//                    cur = splitted.get( i );
                }
            }
        }
        System.out.println( result );
        System.out.println( ( (LinkedList<String>) result ).getFirst() );
        System.out.println( ( (LinkedList<String>) result ).getLast() );
    }

    /*
     * When a < b returns true, else FALSE.
     */

    private static boolean isLexicSmaller( String a, String b ) {

        boolean result = false;
        int i = -1;
        do {
            i++;
            if ( a.charAt( i ) != b.charAt( i ) ) {
                if ( a.charAt( i ) < b.charAt( i ) ) {
                    result = true;
                }
            }
        } while (a.charAt( i ) == b.charAt( i ) && i < ( a.length() - 1 ));
        return result;
    }

}

SAMPLE : Java String.matches()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
 * Copyright 2013. ABN Software. All Rights reserved.<br>
 * <br>
 * Homepage .... http://www.ABNsoft.info<br>
 * <br>
 * Project ..... ABNTest<br>
 * Package ..... ABNTest<br>
 * File name ... StringMatch.java<br>
 * <br>
 * Author ...... Andre<br>
 * Created ..... 18.04.2013<br>
 * <br>
 */

package info.abnsoft.java.trying;

import java.util.regex.Pattern;

/**
 * @author annik
 *
 */

public class StringMatch
{
    public static void main(final String[] args) {
        //
        final StringBuffer sb = new StringBuffer( "<response>\n"+
"    <category>client</category>\n"+
"    <action>Login</action>\n"+
"    <code>1000</code>\n"+
"    <msg>Command completed successfully</msg>\n"+
"    <value>L115:no value</value>\n"+
"    <resData>\n"+
"    </resData>\n"+
"    <cltrid>RM.2013.04.18.1366294770248</cltrid>\n"+
"    <svtrid>RM.2013.04.18.1366294770248-API-SRV</svtrid>\n"+
"    <chksum>8fc683ce8d7772f91ac28224fa3e6cc0</chksum>\n"+
"</response>\n" );
       
        System.out.println(sb.toString());
       
        System.out.println("\n\n======================");
        final String pattern0 = "(?s).*" + "</response>" + ".*";
        System.out.println(pattern0);
       
        if (sb.toString().toLowerCase().matches(pattern0)) {
            System.out.println("MATCH");
        }else {
            System.out.println(" ! FAILED");
        }
       
        System.out.println("\n\n======================");
        final String pattern1 = "(?m)(?s)" + "</response>" + "";
        System.out.println(pattern1);
       
        if (sb.toString().toLowerCase().matches(pattern1)) {
            System.out.println("MATCH");
        }else {
            System.out.println(" ! FAILED");
        }
       
        System.out.println("\n\n======================");
        final String pattern2 = "" + "</response>" + "";
        final Pattern p = Pattern.compile(pattern2, Pattern.MULTILINE+Pattern.DOTALL);
        System.out.println(p.matcher(sb.toString().toLowerCase()).find());  //true


    }
}

that code above will print follow :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<response>
    <category>client</category>
    <action>Login</action>
    <code>1000</code>
    <msg>Command completed successfully</msg>
    <value>L115:no value</value>
    <resData>
    </resData>
    <cltrid>RM.2013.04.18.1366294770248</cltrid>
    <svtrid>RM.2013.04.18.1366294770248-API-SRV</svtrid>
    <chksum>8fc683ce8d7772f91ac28224fa3e6cc0</chksum>
</response>



======================
(?s).*</response>.*
MATCH


======================
(?m)(?s)</response>
 ! FAILED


======================
true

Error with MySQL DATETIME ‘0000-00-00 00:00:00’ can not be represented as java.sql.Timestamp

When I started work with MySQL from Hibernate I got exceptions with approximate content :
… ‘0000-00-00 00:00:00’ …. can not be represented as java.sql.Timestamp

My solution for this bug was following :
As I used bean datasource :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<beans
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <!-- <value>/WEB-INF/database/database.properties</value> -->
        <value>/META-INF/spring/database/database.properties</value>
    </property>
</bean>
 
<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}?zeroDateTimeBehavior=convertToNull" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>
 
</beans>

I added into property URL :

Because I added also in bean id=”sessionFactory” such property :

1
2
3
4
5
6
7
        <property name="hibernateProperties">
            <props>
.....
                <!--  -->
                <prop key="hibernate.connection.zeroDateTimeBehavior">convertToNull</prop>
            </props>
        </property>

that does not help to resolve exception.

MySQL enum in HIBERNATE

How to provide corresponding hibernate Entity and MySQL ENUM type ?

1
enum('Active','Pending','Cancelled','Suspend')

With ANNOTATION :

1
2
@Column(name="status", columnDefinition="enum('Active','Pending','Cancelled','Suspend')")
public String status;

With XML config :

1
2
3
4
5
<property
   name="status"
   column="STATUS"
   type="string"
   not-null="true" />