Tagged: sample Toggle Comment Threads | Keyboard Shortcuts

  • Subinkrishna Gopi 5:56 pm on October 18, 2010 Permalink |
    Tags: , DBMS, , ejb3, entity, hibernate, , ORM, query, sample, session   

    How-to: Write a named query for an entity bean with composite key 

    I was working on an EJB3 project where I had to write an entity bean with a composite primary key. And I needed to write a named query to which had to use a sub set of the composite key. And this is what I did.

    The entity bean and the composite key:

    import javax.persistence.Column;
    import javax.persistence.EmbeddedId;
    import javax.persistence.Entity;
    import javax.persistence.NamedQueries;
    import javax.persistence.NamedQuery;
    import javax.persistence.Table;
    
    @Entity
    @Table (name = "myTable")
    public class MyEntityBean implements Serializable
    {
        @EmbeddedId
        private MyCompositeKey key;
    
        // Other instance members
    
        @Column (name = "value")
        private String value;
    
        // Getters & setters
        ...
    }
    
    import java.io.Serializable;
    import javax.persistence.Column;
    import javax.persistence.Embeddable;
    
    @Embeddable
    public class MyCompositeKey implements Serializable
    {
        @Column (name = "key1", nullable = false)
        private String key1;
    
        @Column (name = "key2", nullable = false)
        private String key2;
    
        // Getters & setters
        ....
    }
    

    The equivalent database table will look like:

    +---------------+--------------+------+-----+---------+-------+
    | Field         | Type         | Null | Key | Default | Extra |
    +---------------+--------------+------+-----+---------+-------+
    | key1          | varchar(255) | NO   | PRI |         |       |
    | key2          | varchar(255) | NO   | PRI |         |       |
    | value         | varchar(255) | YES  |     |         |       |
    +---------------+--------------+------+-----+---------+-------+
    

    Writing a named query which makes use of the elements of the composite key is a li’l tricky. Take a look at the following SQL statement which tries to fetch all the records from the table for a matching key1.

    SELECT * FROM myTable WHERE key1='some value';
    

    Embedding the named query in MyEntityBean.

    @Entity
    @Table (name = "myTable")
    @NamedQueries
    ({
        @NamedQuery(
            name = "myQuery",
            query = "SELECT FROM MyEntityBean b WHERE key.key1 = :key1" )
    })
    public class MyEntityBean implements Serializable
    {
        ...
    }
    

    We should be careful about the use of the variable name in the named query. In the named query, we are supposed to use the name of the composite key exactly the same as what we have specified in the bean.

    This query can be accessed from a session bean with the help of EntityManager.

    import javax.ejb.Remote;
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;
    
    @Remote
    @Stateless (name = "MySessionBean")
    public class MySessionBeanImpl implements SessionBean
    {
        @PersistenceContext
        private EntityManager entityManager;
    
        public void myMethod(String key)
        {
        	Query aQuery = null;
    
        	aQuery = this.entityManager.createNamedQuery("myQuery");
            aQuery.setParameter("key1", key);
    
            List resultList = aQuery.getResultList();
    
            .....
        }
    }
    

    Hope this helps. Have a good day 🙂

    Advertisements
     
  • Subinkrishna Gopi 11:01 am on October 13, 2010 Permalink |
    Tags: , archives, build, , , sample, script, ,   

    How-to: Get timestamp in ANT scripts 

    We use a lot of ANT scripts to build our archives. And archives without version number/timestamp is a big pain. We faced a lot of issues mainly integration issues. This is a small piece of script which can be used to add timestamp to an archive’s name.

    This is done using the tstamp task in ANT. tstamp is highly configurable and uses the java.text.SimpleDateFormat date/time patterns.

    <target name="timestamp.target">
    	<tstamp>
    		<format property="current.time"
    			pattern="yyyyMMdd_HHmmss" />
    		<format property="archive.name"
    			pattern="'MyArchive_'yyyyMMdd_HHmmss'.jar'" />
    	</tstamp>
    	<echo>${current.time}</echo>
    	<echo>${archive.name}</echo>
    </target>
    

    I got the following output when I tried to run the above build script:

    Buildfile: /home/subin/sampleProject/build.xml
    timestamp.target:
         [echo] 20101013_103329
         [echo] MyArchive_20101013_103329.jar
    BUILD SUCCESSFUL
    Total time: 524 milliseconds
    

    So, we have tstamp, which formats (format) the time/date information and assigns the result to the specified property. The echo statements demonstrate how we can use those values further.

    Hope this helps. Have a nice day.

     
  • Subinkrishna Gopi 11:59 am on July 30, 2010 Permalink |
    Tags: , code snippet, commons, cookie, , httpclient, , networking, proxy, sample   

    HttpClient (Apache commons) code sample 

    I was playing around with Apache commons Http utilities the last day. I used to use the java.net.* APIs to satisfy my HTTP(s) needs.

    Here is a sample code which I wrote which takes a URL as input, sets the basic request parameters (e.g. cookie string) and set the proxy settings along with the user credentials.

    import org.apache.commons.httpclient.Credentials;
    import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
    import org.apache.commons.httpclient.Header;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.UsernamePasswordCredentials;
    import org.apache.commons.httpclient.auth.AuthScope;
    import org.apache.commons.httpclient.methods.GetMethod;
    import org.apache.commons.httpclient.params.HttpMethodParams;
    
    public class HttpClientTest
    {
        public static void main(String[] args)
        {
            HttpClient client = null;
            GetMethod getMethod = null;
            int responseCode = -1;
            byte[] responseStream = null;
    
            String urlString = "http://www.facebook.com";
            String cookieString = null;
    
            try
            {
                // Creating the GetMethod instance
                getMethod = new GetMethod(urlString);
    
                // Retries to establish a successful connection the specified number
                // of times if the initial attempts are not successful.
                getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                        new DefaultHttpMethodRetryHandler(1, false));
                getMethod.getParams().setParameter("http.socket.timeout", new Integer(5000));
                getMethod.setRequestHeader(new Header("Cookie", "<COOKIE_STRING>"));
    
                // Creating an HttpClient instance
                client = new HttpClient();
    
                // Proxy settings: Configures the proxy host, port & user
                // credentials and the scope of the credentials.
                client.getHostConfiguration().setProxy("<HOST>", <PORT>);
                Credentials credentials = new UsernamePasswordCredentials
                    ("<USERNAME>", "<PASSWORD>");
                AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
                client.getState().setProxyCredentials(scope, credentials);
    
                // Sets the user-agent for the client instance
                client.getParams().setParameter("http.useragent", "<USER_AGENT>");
    
                // Sends the GET request and gets the response
                responseCode = client.executeMethod(getMethod);
                responseStream = getMethod.getResponseBody();
    
                System.out.println("Response Code: " + responseCode);
                System.out.println("Response Body: \n" + new String(responseStream));
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            finally
            {
                getMethod.releaseConnection();
                client = null;
            }
        }
    }
    

    P.S. Did I mention that this is test code? 🙂

    Note: I was looking for an API set which does make use of its own Socket level implementation. I don’t think HttpClient got it’s own implementation as it claims to be 100% Java. If you know any API set which performs better than java.net.* APIs please feel free to share it.

     
c
Compose new post
j
Next post/Next comment
k
Previous post/Previous comment
r
Reply
e
Edit
o
Show/Hide comments
t
Go to top
l
Go to login
h
Show/Hide help
shift + esc
Cancel