DAO classes and Hibernate

hi all
need help.
i have one dought where is used DAO classes and where is
used Hibernate.i think both r used for data base access ,but why we are
used both.
thanks in advence.

i have one dought where is used DAO classes and where is
used Hibernate.Awesome, we got doubt misused AND misspelled!
i think both r used for data base accesscorrect!
but why we are used both.DAO is a design pattern (concept) and Hibernate is a product (code implementation).
Hibernate is a DAO implementation. That said, you don't need both, in fact you don't need either.

Similar Messages

  • How to retrieve content from DAO Class and process in Controller Class?

    Hello
    This is for the experts.
    What is the best approach to passing a large set of data from Class A to Class B? I have a DAO Class that connects to a database to retrieve data. I tried saving the data in a collection (map) and passing the collection to Class B. The problem here is that the data is may be too large for a collection without increasing the heap size, it could cause out of memory exception. Instead I'd like to pass the data (row by row) on to the "Controller" Class where which will process each row. I am not sure how to do this without using a collection or some sort. Some tips will be much appreciated.
    Note: MVC Rules dictates that Controller cannot call the DAO Class directly, it has to go through the Model which talks directly with the DAO Class.
    Thanks
    Edited by: 875864 on 30-Oct-2011 15:05

    875864 wrote:
    Hello
    This is for the experts.
    What is the best approach to passing a large set of data from Class A to Class B? I have a DAO Class that connects to a database to retrieve data. I tried saving the data in a collection (map) and passing the collection to Class B. The problem here is that the data is may be too large for a collection without increasing the heap size, it could cause out of memory exception. Instead I'd like to pass the data (row by row) on to the "Controller" Class where which will process each row. I am not sure how to do this without using a collection or some sort. Some tips will be much appreciated.
    Note: MVC Rules dictates that Controller cannot call the DAO Class directly, it has to go through the Model which talks directly with the DAO Class.
    Thanks
    Edited by: 875864 on 30-Oct-2011 15:05if its a large set of data, and is fetched from DB and you are sure that it is too large and chances of getting out of memory exception then why you are passing it over request.
    If the data is fetched based on some filter criteria, then just pass the filter criteria from class A to class B, and fetch the data from DB based on the filter criteria in class B.

  • Where clause and order by to DAO classes

    Hi
    Is it ok(I mean design wise) to pass the 'where clause' conditions and order by clause as a parameter to the method of DAO class?

    Well, I would suggest you write seperate methods in your dao , one to select data without the where clause and one to select data with the where clause thrown in. If you have different 'where' clauses for selecting different kinds of data, have that many dao methods. The dao methods being specific know exactly what is the data that's coming in.
    Lets assume you have a list of purchase orders and each purchase order is indetified by a unique id called PURCHASE_ORDER_ID.
    1. The following code would populate a purchase order's details given an id.
    private statis final String QUERY_1 = "select * from PURCHASE_ORDERS where PURCHASE_ORDER_ID = ? ";
    PurchaseOrderModel getPurchaseOrderData(long poId){
         //get a prepared statement from your connection
         PreparedStatement pst = conn.prepareStatement(QUERY_1);
         //set the poId passed as params to your query
         pst.setLong(1, poId);
         ResultSet rs = pst.executeQuery();
         if(rs.next()){
              //populate data into a model          
         finally{
              //clean up resources
         return model;    
    }2. The following code would return a list of PurchaseOrderModel's whose shipping date falls between a set of dates selected by the user.
    private statis final String QUERY_2 = "select * from PURCHASE_ORDERS where SHIPPING_DATE between ? and ? ";
    PurchaseOrderModel getPurchaseOrdersBetweenDates(list bindValues){
         //get a prepared statement from your connection
         PreparedStatement pst = conn.prepareStatement(QUERY_1);
         //set the dates passed as params to your query
         //we know that the List ought to contain only 2 dates
         pst.setDate(1, (Date)bindValues.get(0));
         pst.setDate(2, (Date)bindValues.get(1));
         ResultSet rs = pst.executeQuery();
         if(rs.next()){
              //iterate and populate data into a model          
              //add model to a list
         finally{
              //clean up resources
         return list;    
         3. This is more interesting - the dao method searches a list of Purchase Orders starting with a set of specific words. The words themselves may be one or many. This means that the number of '?' in your prepared statement may be dynamic. Each element of the list is a String that contains the start substring of a purcahse order name. For example - the list may contain elements like ["a", "ab", "c", "gh"] and the dao method returns all purchase order starting with these names.
    private statis final String QUERY_3 = "select * from PURCHASE_ORDERS where ";
    PurchaseOrderModel getPurchaseOrderNameMatches(list bindValues){
         //construct the query dynamically
         StringBuffer query = new StringBuffer(QUERY_3);
         int count = 0;
         for(Iterator itr = bindValues.iterator(); itr.hasNext();;){
              String value = (String)itr.next();
              query.append ("name like 'value%' ");
              if (count != 0 and (count+1 != bindValues.length)){
                   query.append(" or ");
              count ++;          
         //get a prepared statement from your connection
         PreparedStatement pst = conn.prepareStatement(query.toString());     
         ResultSet rs = pst.executeQuery();
         if(rs.next()){
              //iterate and populate data into a model          
              //add model to a list
         finally{
              //clean up resources
         return list;    
    To sum up,
    1. You need as many methods as you have different kinds of searches (one method for each kind of 'where' clause).
    2. The ejb/business layer would examine the data and decide on which method to call.
    3. Increases coding effort, but makes the code clean and readable. Each layer does it's job. Thus we dont have ejbs forming 'where' clauses and so on.
    Having said that, it really is your decision - you should take into consideration the following factors -
    1. How big is the project ? If its a huge codebase developed by many people, then segregate the responsibilities clearly in each layer as I have outlined. For a small scale project, you could go with your approach.
    2. Whats the take on maintenance and future add-ons ? Do you see the codebase growing with time ?
    3. Is your project a commercial one - is it a product that needs to be maintained or is it a one-off development - develop once and you are done with it.
    4. What are the design considerations ? Is somebody going to audit code for quality ? Or is it a academic one ?
    You should take into account all these before deciding to go one way or the other.
    A general thumb rule should be that you should be convinced that your code readable (maintainable), scalable and efficient. Anything that you do towards these ends is good code/design despite what people/books/patterns say, IMO.
    cheers,
    ram.

  • How to store an image into MySQL db using BlazeDS and Hibernate?

    Hi!
    I am using Flash Builder 4.6, BlazeDS, and Hibernate. How to store a webcam snapshot into the MySql Database. I stored Form Items by using RemoteObject into the database. But I failed to store webcam snapshot. I captured that image on Panel component.I converted that image to ByteArray. Now I want to save that image into the database. Please help me in this regard.
    thanks in advance.
    Here the Code:
    VisitorEntryForm.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <mx:TitleWindow
              xmlns:mx="http://www.adobe.com/2006/mxml"
              xmlns:vo="com.visitor.vo.*"
              width="600"
              height="300"
              defaultButton="{submitButton}"
              showCloseButton="true"
              creationComplete="creationCompleteHandler();"
              close="PopUpManager.removePopUp(this);"
              title="Visitor Entry Form" xmlns:text="flash.text.*">
              <mx:RemoteObject id="saveService" destination="visitorService" result="handleSaveResult(event)" fault="handleFault(event)" showBusyCursor="true" />
              <vo:Visitor id="visitor"
                                               vType="{vTypeField.text}"
                                               vPurpose="{vPurposeField.text}"
                                               vName="{vNameField.text}"
                                               vAddress="{vAddressField.text}"
                                               cPerson="{cPersonField.text}"
                                               cAddress="{cAddressField.text}"
                                     />
                        <mx:Script>
                        <![CDATA[
                        import mx.managers.PopUpManager;
                        import flash.media.Camera;
                        import com.visitor.vo.WebCam;
                        import com.visitor.vo.Base64;
                        import mx.core.UIComponent;
                        import mx.graphics.codec.JPEGEncoder;
                        import mx.controls.Alert;
                        import mx.containers.Canvas;
                        import mx.rpc.events.ResultEvent;
                        import mx.rpc.events.FaultEvent;
                        import mx.events.ValidationResultEvent;
                        import mx.validators.Validator;
                                  [Bindable]
                                  private var webCam: com.visitor.vo.WebCam;
                                  [Bindable]
                                  private var message:String;
                                  [Bindable]
                                  private var formIsValid:Boolean = false;
                                  [Bindable]
                                  public var formIsEmpty:Boolean;
                                  private var focussedFormControl:DisplayObject;
                                  private function handleSaveResult(ev:ResultEvent):void {
                                            clearFormHandler();
                                            validateForm(ev);
                                            Alert.show("Visitor successfully created/updated.", "Information", Alert.OK, null, null, null, Alert.OK);
                                            // Reload the list.
                                            parentApplication.listConsultants.loaderService.getConsultants();
                                            PopUpManager.removePopUp(this);
                                  private function handleFault(ev:FaultEvent):void {
                                            message = "Error: " + ev.fault.faultCode + " \n "
                                                      + "Detail: " + ev.fault.faultDetail + " \n "
                                                      + "Message: " + ev.fault.faultString;
                                  public function saveVisitor():void {
                                            saveService.addUpdateVisitor(visitor);
                                  private function creationCompleteHandler():void {
                                            init();
                                            PopUpManager.centerPopUp(this);
                                            resetFocus();
                                  private function resetFocus():void {
                                            focusManager.setFocus(vTypeField);
                                  public function validateForm(event:Event):void  {
                                            focussedFormControl = event.target as DisplayObject;   
                                            formIsValid = true;
                                            // Check if form is empty
                                            formIsEmpty = (vTypeField.text == "" && vPurposeField.text == "" && vNameField.text == "" && vAddressField.text == "" && cPersonField.text == "" && cAddressField.text == "");
                                            validate(vTypeValidator);               
                                            validate(vPurposeValidator);
                                            validate(vNameValidator);
                                            validate(vAddressValidator);
                                            validate(cPersonValidator);
                                            validate(cAddressValidator);
                                  private function validate(validator:Validator):Boolean {
                                            var validatorSource:DisplayObject = validator.source as DisplayObject;
                                            var suppressEvents:Boolean = (validatorSource != focussedFormControl);
                                            var event:ValidationResultEvent = validator.validate(null, suppressEvents);
                                            var currentControlIsValid:Boolean = (event.type == ValidationResultEvent.VALID);
                                            formIsValid = formIsValid && currentControlIsValid;
                                            return currentControlIsValid;
                                  private function clearFormHandler():void {
                                            // Clear all input fields.
                                            vTypeField.text = "";
                                            vPurposeField.text = "";
                                            vNameField.text = "";
                                            vAddressField.text = "";
                                            cPersonField.text = "";
                                            cAddressField.text = "";
                                            message = "";
                                            // Clear validation error messages.
                                            vTypeField.errorString = "";
                                            vPurposeField.errorString = "";
                                            vNameField.errorString = "";
                                            vAddressField.errorString = "";
                                            cPersonField.errorString = "";
                                            cAddressField.errorString = "";
                                            formIsEmpty = true;
                                            formIsValid = false;
                                            resetFocus();
                                  private function init():void {
                                  webCam = new WebCam(97,97);
                                  var ref:UIComponent = new UIComponent();
                                  preview.removeAllChildren();
                                  preview.addChild(ref);
                                  ref.addChild(webCam);
                                  private function takeSnapshot():void {
                                  imageViewer.visible = true;
                                  imageViewer.width = preview.width;
                                  imageViewer.height = preview.height;
                                  var uiComponent : UIComponent = new UIComponent();
                                  uiComponent.width = webCam.width;
                                  uiComponent.height = webCam.height;
                                  var photoData:Bitmap = webCam.getSnapshot();
                                  var photoBitmap:BitmapData = photoData.bitmapData;
                                  uiComponent.addChild(photoData);
                                  imageViewer.removeAllChildren();
                                  imageViewer.addChild(uiComponent);
                                  private function uploadSnapshot():void
                                            if (imageViewer.getChildren().length > 0)
                                                      var uic:UIComponent = imageViewer.getChildAt(0) as UIComponent;
                                                      var bitmap:Bitmap = uic.getChildAt(0) as Bitmap;
                                                      var jpgEncoder:JPEGEncoder = new JPEGEncoder(75);
                                                      var jpgBytes:ByteArray = jpgEncoder.encode(bitmap.bitmapData);
                                  private function deleteSnapshot():void
                                            imageViewer.removeAllChildren();
                        ]]>
                        </mx:Script>
              <mx:StringValidator id="vTypeValidator"          source="{vTypeField}"          property="text" minLength="2" required="true" />
              <mx:StringValidator id="vPurposeValidator" source="{vPurposeField}"          property="text" minLength="2" required="true" />
              <mx:StringValidator id="vNameValidator"          source="{vNameField}"          property="text" minLength="2" required="true" />
              <mx:StringValidator id="vAddressValidator"          source="{vAddressField}"          property="text" minLength="5" required="true" />
              <mx:StringValidator id="cPersonValidator" source="{cPersonField}"          property="text" minLength="2" required="true" />
              <mx:StringValidator id="cAddressValidator"          source="{cAddressField}"          property="text" minLength="5" required="true" />
              <mx:Grid width="575" height="211">
                        <mx:GridRow width="575" height="211">
                                  <mx:GridItem width="301" height="235">
                                            <mx:Form width="301" height="208">
                                                      <mx:FormItem label="Visitor's Type">
                                                                <mx:ComboBox id="vTypeField" text="{visitor.vType}" change="validateForm(event);" editable="true">
                                                                          <mx:Array>
                                                                                    <mx:String></mx:String>
                                                                                    <mx:String>Contractor</mx:String>
                                                                                    <mx:String>Supplier</mx:String>
                                                                                    <mx:String>Transporter</mx:String>
                                                                                    <mx:String>Plant</mx:String>
                                                                                    <mx:String>Non-Plant</mx:String>
                                                                          </mx:Array>
                                                                </mx:ComboBox>
                                                      </mx:FormItem>
                                                      <mx:FormItem label="Visit Purpose">
                                                                <mx:ComboBox id="vPurposeField" text="{visitor.vPurpose}" change="validateForm(event);" editable="true">
                                                                          <mx:Array>
                                                                                    <mx:String></mx:String>
                                                                                    <mx:String>Official</mx:String>
                                                                                    <mx:String>Personal</mx:String>
                                                                          </mx:Array>
                                                                </mx:ComboBox>
                                                      </mx:FormItem>
                                                      <mx:FormItem label="Visitor's Name">
                                                                <mx:TextInput id="vNameField"  text="{visitor.vName}" change="validateForm(event);"/>
                                                      </mx:FormItem>
                                                      <mx:FormItem label="Address">
                                                                <mx:TextInput id="vAddressField"   text="{visitor.vAddress}" change="validateForm(event);"/>
                                                      </mx:FormItem>
                                                      <mx:FormItem label="Contact Person">
                                                                <mx:TextInput id="cPersonField"  text="{visitor.cPerson}" change="validateForm(event);"/>
                                                      </mx:FormItem>
                                                      <mx:FormItem label="Address">
                                                                <mx:TextInput id="cAddressField"  text="{visitor.cAddress}" change="validateForm(event);"/>
                                                      </mx:FormItem>
                                                      </mx:Form>
                                  </mx:GridItem>
                                  <mx:GridItem width="264" height="193">
                                            <mx:Grid width="241" height="206">
                                                      <mx:GridRow width="100%" height="100%">
                                                                <mx:GridItem width="100%" height="100%" horizontalAlign="center" verticalAlign="middle">
                                                                          <mx:Panel width="100" height="132" title="Snap" id="preview" layout="absolute"/>
                                                                </mx:GridItem>
                                                                <mx:GridItem width="100%" height="100%" horizontalAlign="center" verticalAlign="middle">
                                                                          <mx:Panel width="100" height="132" title="Preview" id="imageViewer"  layout="absolute"/>
                                                                </mx:GridItem>
                                                      </mx:GridRow>
                                                      <mx:GridRow width="100%" height="27" >
                                                                <mx:GridItem width="100%" height="100%" horizontalAlign="center">
                                                                          <mx:Button id="snapshot" x="2" width="106" height="27" label="Snap"
                                                                                                  click="takeSnapshot();"/>
                                                                </mx:GridItem>
                                                                <mx:GridItem width="100%" height="100%" horizontalAlign="center">
                                                                          <mx:Button id="deleteButton" x="1" width="106" height="27" label="Delete"
                                                                                                  click="deleteSnapshot();"/>
                                                                </mx:GridItem>
                                                      </mx:GridRow>
                                            </mx:Grid>
                                  </mx:GridItem>
                        </mx:GridRow>
              </mx:Grid>
              <mx:ControlBar height="40" horizontalAlign="center">
                        <mx:Button label="Save Visitor"          id="submitButton" enabled="{formIsValid}" click="saveVisitor();" />
                        <mx:Button label="Clear form" enabled="{!formIsEmpty}"          click="clearFormHandler();" />
                        <mx:Button label="Cancel" click="PopUpManager.removePopUp(this);"/>
                        <mx:Label width="211" id="state"/>
              </mx:ControlBar>
              <mx:Text text="{message}" fontWeight="bold" width="300"/>
    </mx:TitleWindow>
    ListVisitors.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Panel
              xmlns:mx="http://www.adobe.com/2006/mxml"
              xmlns:view="com.visitor.view.*"
              width="100%"
              height="100%"
              title="Visitor Management System - Found {visitorRecords} visitors."
              creationComplete="loadVisitors();">
              <mx:RemoteObject id="loaderService" destination="visitorService" result="handleLoadResult(event)"          fault="handleFault(event)" showBusyCursor="true" />
              <mx:RemoteObject id="deleteService" destination="visitorService" result="handleDeleteResult(event)"          fault="handleFault(event)" showBusyCursor="true" />
              <mx:Script>
                        <![CDATA[
                                  import com.visitor.vo.Visitor;
                                  import mx.controls.Alert;
                                  import mx.managers.PopUpManager;
                                  import mx.containers.TitleWindow;
                                  import mx.collections.ArrayCollection;
                                  import mx.rpc.events.ResultEvent;
                                  import mx.rpc.events.FaultEvent;
                                  [Bindable]
                                  private var message:String;
                                  [Bindable]
                                  private var visitors:ArrayCollection = new ArrayCollection();
                                  [Bindable]
                                  private var visitorRecords:int = 0;
                                  public function loadVisitors():void {
                                            loaderService.getVisitors();
                                  private function deleteVisitor():void {
                                            if(dataGrid.selectedItem != null) {
                                                      var selectedItem:Visitor = dataGrid.selectedItem as Visitor;
                                                      deleteService.deleteVisitor(selectedItem.visitorId);
                                  private function createVisitor():void {
                                            var titleWindow:VisitorEntryForm = VisitorEntryForm(PopUpManager.createPopUp(this, VisitorEntryForm, true));
                                            titleWindow.setStyle("borderAlpha", 0.9);
                                            titleWindow.formIsEmpty = true;
                                  private function updateVisitor():void {
                                            var titleWindow:VisitorEntryForm = VisitorEntryForm(PopUpManager.createPopUp(this, VisitorEntryForm, true));
                                            titleWindow.setStyle("borderAlpha", 0.9);
                                            titleWindow.visitor = dataGrid.selectedItem as Visitor;
                                            titleWindow.formIsEmpty = false;
                                  private function handleLoadResult(ev:ResultEvent):void {
                                            visitors = ev.result as ArrayCollection;
                                            visitorRecords = visitors.length;
                                  private function handleDeleteResult(ev:ResultEvent):void {
                                            Alert.show("The visitor has been deleted.", "Information", Alert.OK, null, null, null, Alert.OK);
                                            loadVisitors();
                                  private function handleFault(ev:FaultEvent):void {
                                            message = "Error: "
                                                      + ev.fault.faultCode + " - "
                                                      + ev.fault.faultDetail + " - "
                                                      + ev.fault.faultString;
                        ]]>
              </mx:Script>
              <mx:VBox width="100%" height="100%">
                        <mx:Label text="{message}" fontWeight="bold" includeInLayout="false" />
                        <mx:DataGrid
                                  id="dataGrid"
                                  width="100%"
                                  height="100%"
                                  dataProvider="{visitors}"
                                  doubleClickEnabled="true"
                                  doubleClick="updateVisitor()" >
                                  <mx:columns>
                                            <mx:DataGridColumn dataField="visitorId"          headerText="Visitor ID" width="100"/>
                                            <mx:DataGridColumn dataField="vType"                    headerText="Visitor's Type" />
                                            <mx:DataGridColumn dataField="vPurpose"           headerText="Visit Purpose" />
                                            <mx:DataGridColumn dataField="vName"                     headerText="Visitor's Name" />
                                            <mx:DataGridColumn dataField="vAddress"                    headerText="Visitor's Address" />
                                            <mx:DataGridColumn dataField="cPerson"                     headerText="Contact Person" />
                                            <mx:DataGridColumn dataField="cAddress"                    headerText="Contact Address" />
                                            <mx:DataGridColumn dataField="timeIn"                     headerText="Time-In" />
                                            <mx:DataGridColumn dataField="timeOut"                     headerText="Time-Out" />
                                            <mx:DataGridColumn dataField="vPhoto"                     headerText="Visitor's Photo" />
                                  </mx:columns>
                        </mx:DataGrid>
                        <mx:ControlBar horizontalAlign="center">
                                  <mx:Button label="Create Visitor"          click="createVisitor()"          toolTip="Create a new visitor and store it in the database." />
                                  <mx:Button label="Update Visitor"          click="updateVisitor()"           enabled="{dataGrid.selectedItem}" toolTip="Update an existing database visitor." />
                                  <mx:Button label="Delete Visitor"          click="deleteVisitor()"          enabled="{dataGrid.selectedItem}" toolTip="Delete the visitor from the database." />
                                  <mx:Button label="Reload Data"                    click="loadVisitors()"           toolTip="Reload the visitor list from the database." />
                        </mx:ControlBar>
              </mx:VBox>
    </mx:Panel>
    Visitor.as
    package com.visitor.vo
              import mx.controls.Image;
              import spark.primitives.BitmapImage;
              [Bindable]
              [RemoteClass(alias="com.visitor.Visitor")]
              public class Visitor
                        public function Visitor()
                        public var visitorId:Number;
                        public var vType:String;
                        public var vPurpose:String;
                        public var vName:String;
                        public var vAddress:String;
                        public var cPerson:String;
                        public var cAddress:String;
                        public var timeIn:Date;
                        public var timeOut:Date;
                       public var vPhoto: Image;
    Visitor.java
    package com.visitor;
    import java.sql.Blob;
    import java.sql.Timestamp;
    import javax.persistence.Basic;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.NamedQueries;
    import javax.persistence.NamedQuery;
    import javax.persistence.Table;
    import org.hibernate.annotations.Index;
    @Entity
    @Table(name = "visitors")
    @NamedQueries( {
                        @NamedQuery(name = "visitors.findAll", query = "from Visitor"),
                        @NamedQuery(name = "visitors.byId", query = "select v from Visitor v where v.visitorId= :visitorId") })
    public class Visitor {
              @Id
              @GeneratedValue(strategy = GenerationType.AUTO)
              @Column(name = "visitorId", nullable = false)
              private Long visitorId;
              @Basic
              @Index(name = "vType_idx_1")
              @Column(name = "vType", nullable = true, unique = false)
              private String vType;
              @Basic
              @Column(name = "vPurpose", nullable = true, unique = false)
              private String vPurpose;
              @Basic
              @Column(name = "vName", nullable = true, unique = false)
              private String vName;
              @Basic
              @Column(name = "vAddress", nullable = true, unique = false)
              private String vAddress;
              @Basic
              @Column(name = "cPerson", nullable = true, unique = false)
              private String cPerson;
              @Basic
              @Column(name = "cAddress", nullable = true, unique = false)
              private String cAddress;
              @Basic
              @Column(name = "timeIn", nullable = false, unique = false)
              private Timestamp timeIn;
              @Basic
              @Column(name = "timeOut", nullable = true, unique = false)
              private Timestamp timeOut;
              @Basic
              @Column(name = "vPhoto", nullable = true, unique = false)
              private Blob vPhoto;
              public Visitor() {
                        super();
              public Long getVisitorId() {
                        return visitorId;
              public void setVisitorId(Long visitorId) {
                        this.visitorId = visitorId;
              public String getvType() {
                        return vType;
              public void setvType(String vType) {
                        this.vType = vType;
              public String getvPurpose() {
                        return vPurpose;
              public void setvPurpose(String vPurpose) {
                        this.vPurpose = vPurpose;
              public String getvName() {
                        return vName;
              public void setvName(String vName) {
                        this.vName = vName;
              public String getvAddress() {
                        return vAddress;
              public void setvAddress(String vAddress) {
                        this.vAddress = vAddress;
              public String getcPerson() {
                        return cPerson;
              public void setcPerson(String cPerson) {
                        this.cPerson = cPerson;
              public String getcAddress() {
                        return cAddress;
              public void setcAddress(String cAddress) {
                        this.cAddress = cAddress;
              public Timestamp getTimeIn() {
                        return timeIn;
              public void setTimeIn(Timestamp timeIn) {
                        this.timeIn = timeIn;
              public Timestamp getTimeOut() {
                        return timeOut;
              public void setTimeOut(Timestamp timeOut) {
                        this.timeOut = timeOut;
              public Blob getvPhoto() {
                        return vPhoto;
              public void setvPhoto(Blob vPhoto) {
                        this.vPhoto = vPhoto;
    VisitorService.java
    package com.visitor;
    import java.sql.Timestamp;
    import java.util.Date;
    import java.util.List;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.EntityTransaction;
    import javax.persistence.Persistence;
    import javax.persistence.Query;
    import org.apache.log4j.Logger;
    public class VisitorService {
              private static final String PERSISTENCE_UNIT = "visitor_db";
              private static Logger logger = Logger.getLogger(VisitorService.class);
              public VisitorService() {
                        super();
              public List<Visitor> getvisitors() {
                        logger.debug("** getVisitors called...");
                        EntityManagerFactory entityManagerFactory = Persistence
                                            .createEntityManagerFactory(PERSISTENCE_UNIT);
                        EntityManager em = entityManagerFactory.createEntityManager();
                        Query findAllQuery = em.createNamedQuery("visitors.findAll");
                        List<Visitor> visitors = findAllQuery.getResultList();
                        if (visitors != null)
                                  logger.debug("** Found " + visitors.size() + " records:");
                        return visitors;
              public void addUpdateVisitor(Visitor visitor) throws Exception {
                        logger.debug("** addUpdateVisitor called...");
                        EntityManagerFactory emf = Persistence
                                            .createEntityManagerFactory(PERSISTENCE_UNIT);
                        EntityManager em = emf.createEntityManager();
                        // When passing Boolean and Number values from the Flash client to a
                        // Java object, Java interprets null values as the default values for
                        // primitive types; for example, 0 for double, float, long, int, short,
                        // byte.
                        if (visitor.getVisitorId() == null          || visitor.getVisitorId() == 0) {
                                  // New consultant is created
                                  visitor.setVisitorId(null);
                                  visitor.setTimeIn(new Timestamp(new Date().getTime()));
                        } else {
                                  visitor.setTimeOut(new Timestamp(new Date().getTime()));
                                  // Existing consultant is updated - do nothing.
                        EntityTransaction tx = em.getTransaction();
                        tx.begin();
                        try {
                                  em.merge(visitor);
                                  tx.commit();
                        } catch (Exception e) {
                                  logger.error("** Error: " + e.getMessage());
                                  tx.rollback();
                                  throw new Exception(e.getMessage());
                        } finally {
                                  logger.info("** Closing Entity Manager.");
                                  em.close();
              public void deleteVisitor(Long visitorId) {
                        logger.debug("** deleteVisitor called...");
                        EntityManagerFactory emf = Persistence
                                            .createEntityManagerFactory(PERSISTENCE_UNIT);
                        EntityManager em = emf.createEntityManager();
                        Query q = em.createNamedQuery("visitors.byId");
                        q.setParameter("visitorId", visitorId);
                        Visitor visitor = (Visitor) q.getSingleResult();
                        if (visitor != null) {
                                  EntityTransaction tx = em.getTransaction();
                                  tx.begin();
                                  try {
                                            em.remove(visitor);
                                            tx.commit();
                                  } catch (Exception e) {
                                            logger.error("** Error: " + e.getMessage());
                                            tx.rollback();
                                  } finally {
                                            logger.info("** Closing Entity Manager.");
                                            em.close();
    remoting-config.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <service id="remoting-service" class="flex.messaging.services.RemotingService">
              <adapters>
                        <adapter-definition id="java-object"
                                  class="flex.messaging.services.remoting.adapters.JavaAdapter"
                                  default="true" />
              </adapters>
              <default-channels>
                        <channel ref="my-amf" />
              </default-channels>
              <!-- ADC Demo application -->
              <destination id="visitorService">
                        <properties>
                                  <source>com.visitor.VisitorService</source>
                        </properties>
              </destination>
    </service>

    Hi!
    I am using Flash Builder 4.6, BlazeDS, and Hibernate. How to store a webcam snapshot into the MySql Database. I stored Form Items by using RemoteObject into the database. But I failed to store webcam snapshot. I captured that image on Panel component.I converted that image to ByteArray. Now I want to save that image into the database. Please help me in this regard.
    thanks in advance.
    Here the Code:
    VisitorEntryForm.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <mx:TitleWindow
              xmlns:mx="http://www.adobe.com/2006/mxml"
              xmlns:vo="com.visitor.vo.*"
              width="600"
              height="300"
              defaultButton="{submitButton}"
              showCloseButton="true"
              creationComplete="creationCompleteHandler();"
              close="PopUpManager.removePopUp(this);"
              title="Visitor Entry Form" xmlns:text="flash.text.*">
              <mx:RemoteObject id="saveService" destination="visitorService" result="handleSaveResult(event)" fault="handleFault(event)" showBusyCursor="true" />
              <vo:Visitor id="visitor"
                                               vType="{vTypeField.text}"
                                               vPurpose="{vPurposeField.text}"
                                               vName="{vNameField.text}"
                                               vAddress="{vAddressField.text}"
                                               cPerson="{cPersonField.text}"
                                               cAddress="{cAddressField.text}"
                                     />
                        <mx:Script>
                        <![CDATA[
                        import mx.managers.PopUpManager;
                        import flash.media.Camera;
                        import com.visitor.vo.WebCam;
                        import com.visitor.vo.Base64;
                        import mx.core.UIComponent;
                        import mx.graphics.codec.JPEGEncoder;
                        import mx.controls.Alert;
                        import mx.containers.Canvas;
                        import mx.rpc.events.ResultEvent;
                        import mx.rpc.events.FaultEvent;
                        import mx.events.ValidationResultEvent;
                        import mx.validators.Validator;
                                  [Bindable]
                                  private var webCam: com.visitor.vo.WebCam;
                                  [Bindable]
                                  private var message:String;
                                  [Bindable]
                                  private var formIsValid:Boolean = false;
                                  [Bindable]
                                  public var formIsEmpty:Boolean;
                                  private var focussedFormControl:DisplayObject;
                                  private function handleSaveResult(ev:ResultEvent):void {
                                            clearFormHandler();
                                            validateForm(ev);
                                            Alert.show("Visitor successfully created/updated.", "Information", Alert.OK, null, null, null, Alert.OK);
                                            // Reload the list.
                                            parentApplication.listConsultants.loaderService.getConsultants();
                                            PopUpManager.removePopUp(this);
                                  private function handleFault(ev:FaultEvent):void {
                                            message = "Error: " + ev.fault.faultCode + " \n "
                                                      + "Detail: " + ev.fault.faultDetail + " \n "
                                                      + "Message: " + ev.fault.faultString;
                                  public function saveVisitor():void {
                                            saveService.addUpdateVisitor(visitor);
                                  private function creationCompleteHandler():void {
                                            init();
                                            PopUpManager.centerPopUp(this);
                                            resetFocus();
                                  private function resetFocus():void {
                                            focusManager.setFocus(vTypeField);
                                  public function validateForm(event:Event):void  {
                                            focussedFormControl = event.target as DisplayObject;   
                                            formIsValid = true;
                                            // Check if form is empty
                                            formIsEmpty = (vTypeField.text == "" && vPurposeField.text == "" && vNameField.text == "" && vAddressField.text == "" && cPersonField.text == "" && cAddressField.text == "");
                                            validate(vTypeValidator);               
                                            validate(vPurposeValidator);
                                            validate(vNameValidator);
                                            validate(vAddressValidator);
                                            validate(cPersonValidator);
                                            validate(cAddressValidator);
                                  private function validate(validator:Validator):Boolean {
                                            var validatorSource:DisplayObject = validator.source as DisplayObject;
                                            var suppressEvents:Boolean = (validatorSource != focussedFormControl);
                                            var event:ValidationResultEvent = validator.validate(null, suppressEvents);
                                            var currentControlIsValid:Boolean = (event.type == ValidationResultEvent.VALID);
                                            formIsValid = formIsValid && currentControlIsValid;
                                            return currentControlIsValid;
                                  private function clearFormHandler():void {
                                            // Clear all input fields.
                                            vTypeField.text = "";
                                            vPurposeField.text = "";
                                            vNameField.text = "";
                                            vAddressField.text = "";
                                            cPersonField.text = "";
                                            cAddressField.text = "";
                                            message = "";
                                            // Clear validation error messages.
                                            vTypeField.errorString = "";
                                            vPurposeField.errorString = "";
                                            vNameField.errorString = "";
                                            vAddressField.errorString = "";
                                            cPersonField.errorString = "";
                                            cAddressField.errorString = "";
                                            formIsEmpty = true;
                                            formIsValid = false;
                                            resetFocus();
                                  private function init():void {
                                  webCam = new WebCam(97,97);
                                  var ref:UIComponent = new UIComponent();
                                  preview.removeAllChildren();
                                  preview.addChild(ref);
                                  ref.addChild(webCam);
                                  private function takeSnapshot():void {
                                  imageViewer.visible = true;
                                  imageViewer.width = preview.width;
                                  imageViewer.height = preview.height;
                                  var uiComponent : UIComponent = new UIComponent();
                                  uiComponent.width = webCam.width;
                                  uiComponent.height = webCam.height;
                                  var photoData:Bitmap = webCam.getSnapshot();
                                  var photoBitmap:BitmapData = photoData.bitmapData;
                                  uiComponent.addChild(photoData);
                                  imageViewer.removeAllChildren();
                                  imageViewer.addChild(uiComponent);
                                  private function uploadSnapshot():void
                                            if (imageViewer.getChildren().length > 0)
                                                      var uic:UIComponent = imageViewer.getChildAt(0) as UIComponent;
                                                      var bitmap:Bitmap = uic.getChildAt(0) as Bitmap;
                                                      var jpgEncoder:JPEGEncoder = new JPEGEncoder(75);
                                                      var jpgBytes:ByteArray = jpgEncoder.encode(bitmap.bitmapData);
                                  private function deleteSnapshot():void
                                            imageViewer.removeAllChildren();
                        ]]>
                        </mx:Script>
              <mx:StringValidator id="vTypeValidator"          source="{vTypeField}"          property="text" minLength="2" required="true" />
              <mx:StringValidator id="vPurposeValidator" source="{vPurposeField}"          property="text" minLength="2" required="true" />
              <mx:StringValidator id="vNameValidator"          source="{vNameField}"          property="text" minLength="2" required="true" />
              <mx:StringValidator id="vAddressValidator"          source="{vAddressField}"          property="text" minLength="5" required="true" />
              <mx:StringValidator id="cPersonValidator" source="{cPersonField}"          property="text" minLength="2" required="true" />
              <mx:StringValidator id="cAddressValidator"          source="{cAddressField}"          property="text" minLength="5" required="true" />
              <mx:Grid width="575" height="211">
                        <mx:GridRow width="575" height="211">
                                  <mx:GridItem width="301" height="235">
                                            <mx:Form width="301" height="208">
                                                      <mx:FormItem label="Visitor's Type">
                                                                <mx:ComboBox id="vTypeField" text="{visitor.vType}" change="validateForm(event);" editable="true">
                                                                          <mx:Array>
                                                                                    <mx:String></mx:String>
                                                                                    <mx:String>Contractor</mx:String>
                                                                                    <mx:String>Supplier</mx:String>
                                                                                    <mx:String>Transporter</mx:String>
                                                                                    <mx:String>Plant</mx:String>
                                                                                    <mx:String>Non-Plant</mx:String>
                                                                          </mx:Array>
                                                                </mx:ComboBox>
                                                      </mx:FormItem>
                                                      <mx:FormItem label="Visit Purpose">
                                                                <mx:ComboBox id="vPurposeField" text="{visitor.vPurpose}" change="validateForm(event);" editable="true">
                                                                          <mx:Array>
                                                                                    <mx:String></mx:String>
                                                                                    <mx:String>Official</mx:String>
                                                                                    <mx:String>Personal</mx:String>
                                                                          </mx:Array>
                                                                </mx:ComboBox>
                                                      </mx:FormItem>
                                                      <mx:FormItem label="Visitor's Name">
                                                                <mx:TextInput id="vNameField"  text="{visitor.vName}" change="validateForm(event);"/>
                                                      </mx:FormItem>
                                                      <mx:FormItem label="Address">
                                                                <mx:TextInput id="vAddressField"   text="{visitor.vAddress}" change="validateForm(event);"/>
                                                      </mx:FormItem>
                                                      <mx:FormItem label="Contact Person">
                                                                <mx:TextInput id="cPersonField"  text="{visitor.cPerson}" change="validateForm(event);"/>
                                                      </mx:FormItem>
                                                      <mx:FormItem label="Address">
                                                                <mx:TextInput id="cAddressField"  text="{visitor.cAddress}" change="validateForm(event);"/>
                                                      </mx:FormItem>
                                                      </mx:Form>
                                  </mx:GridItem>
                                  <mx:GridItem width="264" height="193">
                                            <mx:Grid width="241" height="206">
                                                      <mx:GridRow width="100%" height="100%">
                                                                <mx:GridItem width="100%" height="100%" horizontalAlign="center" verticalAlign="middle">
                                                                          <mx:Panel width="100" height="132" title="Snap" id="preview" layout="absolute"/>
                                                                </mx:GridItem>
                                                                <mx:GridItem width="100%" height="100%" horizontalAlign="center" verticalAlign="middle">
                                                                          <mx:Panel width="100" height="132" title="Preview" id="imageViewer"  layout="absolute"/>
                                                                </mx:GridItem>
                                                      </mx:GridRow>
                                                      <mx:GridRow width="100%" height="27" >
                                                                <mx:GridItem width="100%" height="100%" horizontalAlign="center">
                                                                          <mx:Button id="snapshot" x="2" width="106" height="27" label="Snap"
                                                                                                  click="takeSnapshot();"/>
                                                                </mx:GridItem>
                                                                <mx:GridItem width="100%" height="100%" horizontalAlign="center">
                                                                          <mx:Button id="deleteButton" x="1" width="106" height="27" label="Delete"
                                                                                                  click="deleteSnapshot();"/>
                                                                </mx:GridItem>
                                                      </mx:GridRow>
                                            </mx:Grid>
                                  </mx:GridItem>
                        </mx:GridRow>
              </mx:Grid>
              <mx:ControlBar height="40" horizontalAlign="center">
                        <mx:Button label="Save Visitor"          id="submitButton" enabled="{formIsValid}" click="saveVisitor();" />
                        <mx:Button label="Clear form" enabled="{!formIsEmpty}"          click="clearFormHandler();" />
                        <mx:Button label="Cancel" click="PopUpManager.removePopUp(this);"/>
                        <mx:Label width="211" id="state"/>
              </mx:ControlBar>
              <mx:Text text="{message}" fontWeight="bold" width="300"/>
    </mx:TitleWindow>
    ListVisitors.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Panel
              xmlns:mx="http://www.adobe.com/2006/mxml"
              xmlns:view="com.visitor.view.*"
              width="100%"
              height="100%"
              title="Visitor Management System - Found {visitorRecords} visitors."
              creationComplete="loadVisitors();">
              <mx:RemoteObject id="loaderService" destination="visitorService" result="handleLoadResult(event)"          fault="handleFault(event)" showBusyCursor="true" />
              <mx:RemoteObject id="deleteService" destination="visitorService" result="handleDeleteResult(event)"          fault="handleFault(event)" showBusyCursor="true" />
              <mx:Script>
                        <![CDATA[
                                  import com.visitor.vo.Visitor;
                                  import mx.controls.Alert;
                                  import mx.managers.PopUpManager;
                                  import mx.containers.TitleWindow;
                                  import mx.collections.ArrayCollection;
                                  import mx.rpc.events.ResultEvent;
                                  import mx.rpc.events.FaultEvent;
                                  [Bindable]
                                  private var message:String;
                                  [Bindable]
                                  private var visitors:ArrayCollection = new ArrayCollection();
                                  [Bindable]
                                  private var visitorRecords:int = 0;
                                  public function loadVisitors():void {
                                            loaderService.getVisitors();
                                  private function deleteVisitor():void {
                                            if(dataGrid.selectedItem != null) {
                                                      var selectedItem:Visitor = dataGrid.selectedItem as Visitor;
                                                      deleteService.deleteVisitor(selectedItem.visitorId);
                                  private function createVisitor():void {
                                            var titleWindow:VisitorEntryForm = VisitorEntryForm(PopUpManager.createPopUp(this, VisitorEntryForm, true));
                                            titleWindow.setStyle("borderAlpha", 0.9);
                                            titleWindow.formIsEmpty = true;
                                  private function updateVisitor():void {
                                            var titleWindow:VisitorEntryForm = VisitorEntryForm(PopUpManager.createPopUp(this, VisitorEntryForm, true));
                                            titleWindow.setStyle("borderAlpha", 0.9);
                                            titleWindow.visitor = dataGrid.selectedItem as Visitor;
                                            titleWindow.formIsEmpty = false;
                                  private function handleLoadResult(ev:ResultEvent):void {
                                            visitors = ev.result as ArrayCollection;
                                            visitorRecords = visitors.length;
                                  private function handleDeleteResult(ev:ResultEvent):void {
                                            Alert.show("The visitor has been deleted.", "Information", Alert.OK, null, null, null, Alert.OK);
                                            loadVisitors();
                                  private function handleFault(ev:FaultEvent):void {
                                            message = "Error: "
                                                      + ev.fault.faultCode + " - "
                                                      + ev.fault.faultDetail + " - "
                                                      + ev.fault.faultString;
                        ]]>
              </mx:Script>
              <mx:VBox width="100%" height="100%">
                        <mx:Label text="{message}" fontWeight="bold" includeInLayout="false" />
                        <mx:DataGrid
                                  id="dataGrid"
                                  width="100%"
                                  height="100%"
                                  dataProvider="{visitors}"
                                  doubleClickEnabled="true"
                                  doubleClick="updateVisitor()" >
                                  <mx:columns>
                                            <mx:DataGridColumn dataField="visitorId"          headerText="Visitor ID" width="100"/>
                                            <mx:DataGridColumn dataField="vType"                    headerText="Visitor's Type" />
                                            <mx:DataGridColumn dataField="vPurpose"           headerText="Visit Purpose" />
                                            <mx:DataGridColumn dataField="vName"                     headerText="Visitor's Name" />
                                            <mx:DataGridColumn dataField="vAddress"                    headerText="Visitor's Address" />
                                            <mx:DataGridColumn dataField="cPerson"                     headerText="Contact Person" />
                                            <mx:DataGridColumn dataField="cAddress"                    headerText="Contact Address" />
                                            <mx:DataGridColumn dataField="timeIn"                     headerText="Time-In" />
                                            <mx:DataGridColumn dataField="timeOut"                     headerText="Time-Out" />
                                            <mx:DataGridColumn dataField="vPhoto"                     headerText="Visitor's Photo" />
                                  </mx:columns>
                        </mx:DataGrid>
                        <mx:ControlBar horizontalAlign="center">
                                  <mx:Button label="Create Visitor"          click="createVisitor()"          toolTip="Create a new visitor and store it in the database." />
                                  <mx:Button label="Update Visitor"          click="updateVisitor()"           enabled="{dataGrid.selectedItem}" toolTip="Update an existing database visitor." />
                                  <mx:Button label="Delete Visitor"          click="deleteVisitor()"          enabled="{dataGrid.selectedItem}" toolTip="Delete the visitor from the database." />
                                  <mx:Button label="Reload Data"                    click="loadVisitors()"           toolTip="Reload the visitor list from the database." />
                        </mx:ControlBar>
              </mx:VBox>
    </mx:Panel>
    Visitor.as
    package com.visitor.vo
              import mx.controls.Image;
              import spark.primitives.BitmapImage;
              [Bindable]
              [RemoteClass(alias="com.visitor.Visitor")]
              public class Visitor
                        public function Visitor()
                        public var visitorId:Number;
                        public var vType:String;
                        public var vPurpose:String;
                        public var vName:String;
                        public var vAddress:String;
                        public var cPerson:String;
                        public var cAddress:String;
                        public var timeIn:Date;
                        public var timeOut:Date;
                       public var vPhoto: Image;
    Visitor.java
    package com.visitor;
    import java.sql.Blob;
    import java.sql.Timestamp;
    import javax.persistence.Basic;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.NamedQueries;
    import javax.persistence.NamedQuery;
    import javax.persistence.Table;
    import org.hibernate.annotations.Index;
    @Entity
    @Table(name = "visitors")
    @NamedQueries( {
                        @NamedQuery(name = "visitors.findAll", query = "from Visitor"),
                        @NamedQuery(name = "visitors.byId", query = "select v from Visitor v where v.visitorId= :visitorId") })
    public class Visitor {
              @Id
              @GeneratedValue(strategy = GenerationType.AUTO)
              @Column(name = "visitorId", nullable = false)
              private Long visitorId;
              @Basic
              @Index(name = "vType_idx_1")
              @Column(name = "vType", nullable = true, unique = false)
              private String vType;
              @Basic
              @Column(name = "vPurpose", nullable = true, unique = false)
              private String vPurpose;
              @Basic
              @Column(name = "vName", nullable = true, unique = false)
              private String vName;
              @Basic
              @Column(name = "vAddress", nullable = true, unique = false)
              private String vAddress;
              @Basic
              @Column(name = "cPerson", nullable = true, unique = false)
              private String cPerson;
              @Basic
              @Column(name = "cAddress", nullable = true, unique = false)
              private String cAddress;
              @Basic
              @Column(name = "timeIn", nullable = false, unique = false)
              private Timestamp timeIn;
              @Basic
              @Column(name = "timeOut", nullable = true, unique = false)
              private Timestamp timeOut;
              @Basic
              @Column(name = "vPhoto", nullable = true, unique = false)
              private Blob vPhoto;
              public Visitor() {
                        super();
              public Long getVisitorId() {
                        return visitorId;
              public void setVisitorId(Long visitorId) {
                        this.visitorId = visitorId;
              public String getvType() {
                        return vType;
              public void setvType(String vType) {
                        this.vType = vType;
              public String getvPurpose() {
                        return vPurpose;
              public void setvPurpose(String vPurpose) {
                        this.vPurpose = vPurpose;
              public String getvName() {
                        return vName;
              public void setvName(String vName) {
                        this.vName = vName;
              public String getvAddress() {
                        return vAddress;
              public void setvAddress(String vAddress) {
                        this.vAddress = vAddress;
              public String getcPerson() {
                        return cPerson;
              public void setcPerson(String cPerson) {
                        this.cPerson = cPerson;
              public String getcAddress() {
                        return cAddress;
              public void setcAddress(String cAddress) {
                        this.cAddress = cAddress;
              public Timestamp getTimeIn() {
                        return timeIn;
              public void setTimeIn(Timestamp timeIn) {
                        this.timeIn = timeIn;
              public Timestamp getTimeOut() {
                        return timeOut;
              public void setTimeOut(Timestamp timeOut) {
                        this.timeOut = timeOut;
              public Blob getvPhoto() {
                        return vPhoto;
              public void setvPhoto(Blob vPhoto) {
                        this.vPhoto = vPhoto;
    VisitorService.java
    package com.visitor;
    import java.sql.Timestamp;
    import java.util.Date;
    import java.util.List;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.EntityTransaction;
    import javax.persistence.Persistence;
    import javax.persistence.Query;
    import org.apache.log4j.Logger;
    public class VisitorService {
              private static final String PERSISTENCE_UNIT = "visitor_db";
              private static Logger logger = Logger.getLogger(VisitorService.class);
              public VisitorService() {
                        super();
              public List<Visitor> getvisitors() {
                        logger.debug("** getVisitors called...");
                        EntityManagerFactory entityManagerFactory = Persistence
                                            .createEntityManagerFactory(PERSISTENCE_UNIT);
                        EntityManager em = entityManagerFactory.createEntityManager();
                        Query findAllQuery = em.createNamedQuery("visitors.findAll");
                        List<Visitor> visitors = findAllQuery.getResultList();
                        if (visitors != null)
                                  logger.debug("** Found " + visitors.size() + " records:");
                        return visitors;
              public void addUpdateVisitor(Visitor visitor) throws Exception {
                        logger.debug("** addUpdateVisitor called...");
                        EntityManagerFactory emf = Persistence
                                            .createEntityManagerFactory(PERSISTENCE_UNIT);
                        EntityManager em = emf.createEntityManager();
                        // When passing Boolean and Number values from the Flash client to a
                        // Java object, Java interprets null values as the default values for
                        // primitive types; for example, 0 for double, float, long, int, short,
                        // byte.
                        if (visitor.getVisitorId() == null          || visitor.getVisitorId() == 0) {
                                  // New consultant is created
                                  visitor.setVisitorId(null);
                                  visitor.setTimeIn(new Timestamp(new Date().getTime()));
                        } else {
                                  visitor.setTimeOut(new Timestamp(new Date().getTime()));
                                  // Existing consultant is updated - do nothing.
                        EntityTransaction tx = em.getTransaction();
                        tx.begin();
                        try {
                                  em.merge(visitor);
                                  tx.commit();
                        } catch (Exception e) {
                                  logger.error("** Error: " + e.getMessage());
                                  tx.rollback();
                                  throw new Exception(e.getMessage());
                        } finally {
                                  logger.info("** Closing Entity Manager.");
                                  em.close();
              public void deleteVisitor(Long visitorId) {
                        logger.debug("** deleteVisitor called...");
                        EntityManagerFactory emf = Persistence
                                            .createEntityManagerFactory(PERSISTENCE_UNIT);
                        EntityManager em = emf.createEntityManager();
                        Query q = em.createNamedQuery("visitors.byId");
                        q.setParameter("visitorId", visitorId);
                        Visitor visitor = (Visitor) q.getSingleResult();
                        if (visitor != null) {
                                  EntityTransaction tx = em.getTransaction();
                                  tx.begin();
                                  try {
                                            em.remove(visitor);
                                            tx.commit();
                                  } catch (Exception e) {
                                            logger.error("** Error: " + e.getMessage());
                                            tx.rollback();
                                  } finally {
                                            logger.info("** Closing Entity Manager.");
                                            em.close();
    remoting-config.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <service id="remoting-service" class="flex.messaging.services.RemotingService">
              <adapters>
                        <adapter-definition id="java-object"
                                  class="flex.messaging.services.remoting.adapters.JavaAdapter"
                                  default="true" />
              </adapters>
              <default-channels>
                        <channel ref="my-amf" />
              </default-channels>
              <!-- ADC Demo application -->
              <destination id="visitorService">
                        <properties>
                                  <source>com.visitor.VisitorService</source>
                        </properties>
              </destination>
    </service>

  • Transfer Object in JSF, Spring, and Hibernate

    The application on which I am working deploys the JavaServer Faces, Spring and Hibernate frameworks.
    We are going to use the "transfer object" to move data between J2EE tiers from the front end to the back end and vice versa. In addition, data "types" may need to be converted --
    At the front end, the "type" of the data that are entered by users may not match that in the database table. For example, checkboxes may be marked or left blank by users. The "type" of the checkboxes is "boolean" in the JSF backing bean. However, we have either "Y" or "N" for the corresponding field in the database table.
    The JSF backing bean holds data as well as controller functionality. Of course, the transfer object holds data only.
    With regard to class properties, Is the transfer object an exact copy of the JSF backing bean? And at which tier the data are converted to match their correspoding "types" in the database tables?
    We also have the "data objects" which are exact representation of database tables.
    Thanks for your advices.

    Small example: you can decide in the business layer
    whether to convert it to boolean or Boolean (which
    has a 3rd state: null).But it all goes back to your data model. If your data model supports null for that property, then of course boolean is a poor choice. If that case one could use Boolean. None of this has anything to do with re-usability, which was your objection.
    I think the re-usability question goes back to the data model as well. Suppose your data model says this property is boolean valued. However if your database does not support booleans natively, then you need to map the value for storage in the database. But that is the data persistence layers problem.
    OTOH, suppose your data model says that this property may be 'Y' or 'N'. Then the Java class represent the business object should not have a boolean property, we should make it match the data model.
    However, I think that most cases where people are storing 'Y' or 'N' in a field in the database fall into the first case, where the data model is a boolean and they are working around limitations in the database. There is no reason in that case to perpetuate the same limitations in the Java code.

  • OC4J 10.1.3.2, JPA and Hibernate 3.2 Exception on Deployment

    I can't get my simple web application to deploy in my standalone oc4j container. The European organization that I working for wants to use the new technologies out there. Part of the testing is getting oc4j working with hibernate. My web application works just fine with Toplink, but not with Hibernate3. The same web application in Tomcat works for both. The error that oc4j generates is shown below and really doesn't say much that I can do. I followed this blog instructions.
    http://debupanda.blogspot.com/2007/01/using-hibernate-as-pluggable-ejb-3-jpa.html
    2007-04-23 11:48:57.477 NOTIFICATION Starting application : TestJPA
    2007-04-23 11:48:57.477 NOTIFICATION Initializing ClassLoader(s)
    2007-04-23 11:48:57.477 NOTIFICATION Initializing EJB container
    2007-04-23 11:48:57.477 NOTIFICATION Loading connector(s)
    2007-04-23 11:48:57.524 NOTIFICATION Starting up resource adapters
    2007-04-23 11:48:57.524 NOTIFICATION Initializing EJB sessions
    2007-04-23 11:48:57.524 NOTIFICATION Committing ClassLoader(s)
    2007-04-23 11:48:57.524 NOTIFICATION Initialize TestJPA begins...
    2007-04-23 11:48:57.539 NOTIFICATION Initialize TestJPA ends...
    2007-04-23 11:48:57.539 NOTIFICATION Started application : TestJPA
    2007-04-23 11:48:57.555 NOTIFICATION Binding web application(s) to site default-
    web-site begins...
    2007-04-23 11:48:57.571 NOTIFICATION Binding TestJPA web-module for application
    TestJPA to site default-web-site under context root jpa
    07/04/23 11:48:57 oracle.oc4j.admin.internal.DeployerException: [TestJPA:TestJPA
    ] - Exception creating EntityManagerFactory using PersistenceProvider class org.
    hibernate.ejb.HibernatePersistence for persistence unit TestPU.
    07/04/23 11:48:57 at com.evermind.server.ejb.exception.DeploymentException
    .exceptionCreatingEntityManagerFactory(DeploymentException.java:130)
    07/04/23 11:48:57 at com.evermind.server.ejb.persistence.PersistenceUnitMa
    nagerImpl.createContainerEntityManagerFactory(PersistenceUnitManagerImpl.java:19
    7)
    07/04/23 11:48:57 at com.evermind.server.ejb.persistence.PersistenceUnitMa
    nagerImpl.initializePersistenceUnit(PersistenceUnitManagerImpl.java:159)
    07/04/23 11:48:57 at com.evermind.server.ejb.persistence.PersistenceUnitMa
    nagerImpl.initialize(PersistenceUnitManagerImpl.java:86)
    07/04/23 11:48:57 at com.evermind.server.http.HttpApplication.<init>(HttpA
    pplication.java:733)
    07/04/23 11:48:57 at com.evermind.server.ApplicationStateRunning.getHttpAp
    plication(ApplicationStateRunning.java:414)
    07/04/23 11:48:57 at com.evermind.server.Application.getHttpApplication(Ap
    plication.java:571)
    07/04/23 11:48:57 at com.evermind.server.http.HttpSite$HttpApplicationRunT
    imeReference.createHttpApplicationFromReference(HttpSite.java:1990)
    07/04/23 11:48:57 at com.evermind.server.http.HttpSite$HttpApplicationRunT
    imeReference.<init>(HttpSite.java:1909)
    07/04/23 11:48:57 at com.evermind.server.http.HttpSite.addHttpApplication(
    HttpSite.java:1606)
    07/04/23 11:48:57 at oracle.oc4j.admin.internal.WebApplicationBinder.bindW
    ebApp(WebApplicationBinder.java:238)
    07/04/23 11:48:57 at oracle.oc4j.admin.internal.WebApplicationBinder.bindW
    ebApp(WebApplicationBinder.java:99)
    07/04/23 11:48:57 at oracle.oc4j.admin.internal.ApplicationDeployer.bindWe
    bApp(ApplicationDeployer.java:547)
    07/04/23 11:48:57 at oracle.oc4j.admin.internal.ApplicationDeployer.doDepl
    oy(ApplicationDeployer.java:202)
    07/04/23 11:48:57 at oracle.oc4j.admin.internal.DeployerBase.execute(Deplo
    yerBase.java:93)
    07/04/23 11:48:57 at oracle.oc4j.admin.jmx.server.mbeans.deploy.OC4JDeploy
    erRunnable.doRun(OC4JDeployerRunnable.java:52)
    07/04/23 11:48:57 at oracle.oc4j.admin.jmx.server.mbeans.deploy.DeployerRu
    nnable.run(DeployerRunnable.java:81)
    07/04/23 11:48:57 at com.evermind.util.ReleasableResourcePooledExecutor$My
    Worker.run(ReleasableResourcePooledExecutor.java:298)
    07/04/23 11:48:57 at java.lang.Thread.run(Unknown Source)
    2007-04-23 11:48:57.726 NOTIFICATION Application Deployer for TestJPA FAILED.
    2007-04-23 11:48:57.726 NOTIFICATION Application UnDeployer for TestJPA STARTS.
    2007-04-23 11:48:57.742 NOTIFICATION Removing all web binding(s) for application
    TestJPA from all web site(s)
    07/04/23 11:48:57 SEVERE: ProgressObjectImpl.reportError [TestJPA:TestJPA] - Exc
    eption creating EntityManagerFactory using PersistenceProvider class org.hiberna
    te.ejb.HibernatePersistence for persistence unit TestPU.oracle.oc4j.admin.jmx.sh
    ared.exceptions.InternalException: [TestJPA:TestJPA] - Exception creating Entity
    ManagerFactory using PersistenceProvider class org.hibernate.ejb.HibernatePersis
    tence for persistence unit TestPU.
    at oracle.oc4j.admin.jmx.shared.deploy.NotificationUserData.<init>(Notif
    icationUserData.java:107)
    at oracle.oc4j.admin.internal.Notifier.reportError(Notifier.java:429)
    at oracle.oc4j.admin.internal.DeployerBase.execute(DeployerBase.java:123
    at oracle.oc4j.admin.jmx.server.mbeans.deploy.OC4JDeployerRunnable.doRun
    (OC4JDeployerRunnable.java:52)
    at oracle.oc4j.admin.jmx.server.mbeans.deploy.DeployerRunnable.run(Deplo
    yerRunnable.java:81)
    at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(Relea
    sableResourcePooledExecutor.java:298)
    at java.lang.Thread.run(Unknown Source)
    Caused by: oracle.oc4j.admin.internal.DeployerException: [TestJPA:TestJPA] - Exc
    eption creating EntityManagerFactory using PersistenceProvider class org.hiberna
    te.ejb.HibernatePersistence for persistence unit TestPU.
    at com.evermind.server.ejb.exception.DeploymentException.exceptionCreati
    ngEntityManagerFactory(DeploymentException.java:130)
    at com.evermind.server.ejb.persistence.PersistenceUnitManagerImpl.create
    ContainerEntityManagerFactory(PersistenceUnitManagerImpl.java:197)
    at com.evermind.server.ejb.persistence.PersistenceUnitManagerImpl.initia
    lizePersistenceUnit(PersistenceUnitManagerImpl.java:159)
    at com.evermind.server.ejb.persistence.PersistenceUnitManagerImpl.initia
    lize(PersistenceUnitManagerImpl.java:86)
    at com.evermind.server.http.HttpApplication.<init>(HttpApplication.java:
    733)
    at com.evermind.server.ApplicationStateRunning.getHttpApplication(Applic
    ationStateRunning.java:414)
    at com.evermind.server.Application.getHttpApplication(Application.java:5
    71)
    at com.evermind.server.http.HttpSite$HttpApplicationRunTimeReference.cre
    ateHttpApplicationFromReference(HttpSite.java:1990)
    at com.evermind.server.http.HttpSite$HttpApplicationRunTimeReference.<in
    it>(HttpSite.java:1909)
    at com.evermind.server.http.HttpSite.addHttpApplication(HttpSite.java:16
    06)
    at oracle.oc4j.admin.internal.WebApplicationBinder.bindWebApp(WebApplica
    tionBinder.java:238)
    at oracle.oc4j.admin.internal.WebApplicationBinder.bindWebApp(WebApplica
    tionBinder.java:99)
    at oracle.oc4j.admin.internal.ApplicationDeployer.bindWebApp(Application
    Deployer.java:547)
    at oracle.oc4j.admin.internal.ApplicationDeployer.doDeploy(ApplicationDe
    ployer.java:202)
    at oracle.oc4j.admin.internal.DeployerBase.execute(DeployerBase.java:93)
    ... 4 more
    2007-04-23 11:48:58.225 NOTIFICATION Application UnDeployer for TestJPA COMPLETE
    S.
    07/04/23 11:48:58 WARNING: DeployerRunnable.run [TestJPA:TestJPA] - Exception cr
    eating EntityManagerFactory using PersistenceProvider class org.hibernate.ejb.Hi
    bernatePersistence for persistence unit TestPU.oracle.oc4j.admin.internal.Deploy
    erException: [TestJPA:TestJPA] - Exception creating EntityManagerFactory using P
    ersistenceProvider class org.hibernate.ejb.HibernatePersistence for persistence
    unit TestPU.
    at oracle.oc4j.admin.internal.DeployerBase.execute(DeployerBase.java:126
    at oracle.oc4j.admin.jmx.server.mbeans.deploy.OC4JDeployerRunnable.doRun
    (OC4JDeployerRunnable.java:52)
    at oracle.oc4j.admin.jmx.server.mbeans.deploy.DeployerRunnable.run(Deplo
    yerRunnable.java:81)
    at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(Relea
    sableResourcePooledExecutor.java:298)
    at java.lang.Thread.run(Unknown Source)

    I am not using JDeveloper, the project was created in Netbeans 5.5. I only use the WAR created and Deploy it using the web administration of Oracle 10.1.3.2

  • Parent Child Hierarchy with FDS and Hibernate

    I know my chances of getting heard here are slim, but I am at
    a dead end, so here goes.
    I have a four level hierarchy of objects
    PlanPoint
    ....UserScenario
    ........Scenario
    ............Competitor
    which have bi-directional one-to-many relationships between
    them.
    I have made sure that my hibernate mappings and FDS
    destination are matched and I definitely need to have managed
    associations as the graph of objects will grow large in my
    application (and besides, it is good development practice). So I
    have a fully formed project (or at least I think I do) and I get a
    duplicate object error.
    Right at the bottom I have an alternative that I have tried
    which gives a different error.
    Here is a snippet from my log... it picks up just after the
    message arrives
    2007-02-05 21:21:10,281 INFO [STDOUT] Hibernate: insert into
    COMPETITOR (COMPETITOR_ID, SCENARIO_ID, NAME, X, Y, RADIUS, ACTUAL,
    PROPOSITIONS, ORDER_SIZE, CONVERSION_RATE) values (null, ?, ?, ?,
    2007-02-05 21:21:10,281 INFO [STDOUT] Hibernate: call
    identity()
    2007-02-05 21:21:10,312 INFO [STDOUT] Hibernate: insert into
    SCENARIO (SCENARIO_ID, TITLE, SEQUENCE, POTENTIAL,
    USER_SCENARIO_ID) values (null, ?, ?, ?, ?)
    2007-02-05 21:21:10,312 INFO [STDOUT] Hibernate: call
    identity()
    2007-02-05 21:21:10,359 INFO [STDOUT] Hibernate: insert into
    USER_SCENARIO (USER_SCENARIO_ID, TITLE, PLANPOINT_ID, AUTHOR)
    values (null, ?, ?, ?)
    2007-02-05 21:21:10,359 INFO [STDOUT] Hibernate: call
    identity()
    2007-02-05 21:21:10,406 INFO [STDOUT] [Flex] Serializing
    AMF/RTMP response
    Version: 3
    (Command method=_error (0) trxId=8)
    (Typed Object #0 'flex.messaging.messages.ErrorMessage')
    rootCause = (Typed Object #1
    'org.hibernate.NonUniqueObjectException')
    throwables = (Array #2)
    [0] = (Ref #1)
    localizedMessage = "a different object with the same
    identifier value was already associated with the session:
    [pmco.pojos.Competitor#0]"
    message = "a different object with the same identifier value
    was already associated with the session: [pmco.pojos.Competitor#0]"
    identifier = 0
    cause = null
    throwableCount = 1
    entityName = "pmco.pojos.Competitor"
    messages = (Array #3)
    [0] = "a different object with the same identifier value was
    already associated with the session"
    destination = "competitor.hibernate"
    headers = (Object #4)
    correlationId = "BFAF11E0-6121-54BB-A836-93C81DAE7772"
    faultString = "Could not invoke sync method on data adapter
    for destination 'userscenario.hibernate' due to the following
    error: class org.hibernate.NonUniqueObjectException:a different
    object with the same identifier value was already associated with
    the session: [pmco.pojos.Competitor#0]."
    messageId = "78CB9396-9618-519F-8DB0-70D4E53357FE"
    faultCode = "Server.Processing"
    timeToLive = 0.0
    extendedData = null
    faultDetail = null
    clientId = null
    timestamp = 1.17071047039E12
    body = null
    Anyone got any ideas?
    I would provide my mappings and destinations but I can't fit
    them in a message

    Hi,
    thanks for the reply it was very helpful. I came to pretty
    much the same conclusion and started on the path of a re-write of
    the hibernate assembler myself. As far as I can tell the Hibernate
    Assembler is a Java Assembler, so there didn't seem much difference
    to me between fixing that one and writing another one. Adobe ship
    the code.
    Bit of a cheeky request, but I don't suppose you would be
    willing to share your assembler layer so I have a template against
    which to work? Biggest problem with this sort of activity is a lack
    of examples which makes it very slow going and largely trial and
    error.
    If you would like to know more about our application I will
    provide contact details so we can discuss.
    Simon
    PS Jeff Vroom posted a reply saying that the Adobe Hibernate
    Assembler didn't work properly with hierarchical data (which I
    imagine is every real application in the world), personally I think
    Adobe should fix it or pull it.
    http://tech.groups.yahoo.com/group/flexcoders/message/63961

  • Mapping data model to java classes and Interface.

    Need help in mappning my data model into java classes;
    Here are some of the details:
    Table, Poll:
    PollID int
    PollName varchar
    BusinessUnit varchar
    DisplaySchemeID int // reference to DisplayScheme table.
    Table, DisplayScheme
    DisplaySchemeID
    DisplaySchemeName
    etc
    Table, URL
    UrlID
    UrlName
    UrlDesc
    Table, PollURL
    PollURLID
    PollID
    UrlID
    PublishDate
    etc
    Table, Tag
    TagID
    TagName
    PollID
    So, a POLL is associate with a DisplayScheme.
    A Poll can have many URLs and a URL can be associate with many Polls , mapped in the PollURL table.
    and same is the situation with tags.
    Essentially I want to learn how to do one to many mappning and many to many mapping.
    Also to add, since I plan to use Ibatis for OR mapping.
    So I should a Parameter call to map for creaint a Poll. And to create a poll the form submitted will have:
    - PollName
    - URLs ( multiple )
    - one display scheme.
    - Tags ( many )
    So if you can show how to write a DAO createPoll method, then it would be great.
    Not sure if am asking a lot, but this would be a great example to move forward.

    The below is the sample DAO Class.
    For your case, you have to create your own PollBean with getters and setters and just pass the object to the method
    public int create(Connection con, ProjectBean projectBean) throws SQLException {
              int result = 0;
              String insertQuery = " INSERT INTO" +
                        " M_PROJECT(" +
                        " PROJECT_ID," +
                        " PROJECT_NAME," +
                        " PROJECT_DESCRIPTION) " +
                        " VALUES(?,?,?,?)";          
              initPrepareStmt(con, insertQuery);
              setString(projectBean.getProjectID());
              setString(projectBean.getProjectName());
              if(projectBean.getProjectDescription().equals("")){
                   setString(" ");
              }else{
                   setString(projectBean.getProjectDescription());
              result = executeUpdate();          
         return result;
         }

  • How to handle blob data with java and mysql and hibernate

    Dear all,
    I am using java 1.6 and mysql 5.5 and hibernate 3.0 . Some time i use blob data type . Earlier my project's data base was oracle 10g but now i am converting it to Mysql and now i am facing problem to save and fetch blob data to mysql database . Can anybody give me the source code for blob handling with java+Mysql+Hibernate
    now my code is :--
    ==================================================
    *.hbm.xml :--
    <property name="image" column="IMAGE" type="com.shrisure.server.usertype.BinaryBlobType" insert="true" update="true" lazy="false"/>
    ===================================================
    *.java :--
    package com.shrisure.server.usertype;
    import java.io.OutputStream;
    import java.io.Serializable;
    import java.sql.Blob;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Types;
    import javax.naming.InitialContext;
    import javax.sql.DataSource;
    import oracle.sql.BLOB;
    import org.hibernate.HibernateException;
    import org.hibernate.usertype.UserType;
    import org.jboss.resource.adapter.jdbc.WrappedConnection;
    import com.google.gwt.user.client.rpc.IsSerializable;
    public class BinaryBlobType implements UserType, java.io.Serializable, IsSerializable {
    private static final long serialVersionUID = 1111222233331231L;
    public int[] sqlTypes() {
    return new int[] { Types.BLOB };
    public Class returnedClass() {
    return byte[].class;
    public boolean equals(Object x, Object y) {
    return (x == y) || (x != null && y != null && java.util.Arrays.equals((byte[]) x, (byte[]) y));
    public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
    BLOB tempBlob = null;
    WrappedConnection wc = null;
    try {
    if (value != null) {
    Connection oracleConnection = st.getConnection();
    if (oracleConnection instanceof oracle.jdbc.driver.OracleConnection) {
    tempBlob = BLOB.createTemporary(oracleConnection, true, BLOB.DURATION_SESSION);
    if (oracleConnection instanceof org.jboss.resource.adapter.jdbc.WrappedConnection) {
    InitialContext ctx = new InitialContext();
    DataSource dataSource = (DataSource) ctx.lookup("java:/DefaultDS");
    Connection dsConn = dataSource.getConnection();
    wc = (WrappedConnection) dsConn;
    // with getUnderlying connection method , cast it to Oracle
    // Connection
    oracleConnection = wc.getUnderlyingConnection();
    tempBlob = BLOB.createTemporary(oracleConnection, true, BLOB.DURATION_SESSION);
    tempBlob.open(BLOB.MODE_READWRITE);
    OutputStream tempBlobWriter = tempBlob.getBinaryOutputStream();// setBinaryStream(1);
    tempBlobWriter.write((byte[]) value);
    tempBlobWriter.flush();
    tempBlobWriter.close();
    tempBlob.close();
    st.setBlob(index, tempBlob);
    } else {
    st.setBlob(index, BLOB.empty_lob());
    } catch (Exception exp) {
    if (tempBlob != null) {
    tempBlob.freeTemporary();
    exp.printStackTrace();
    st.setBlob(index, BLOB.empty_lob());
    // throw new RuntimeException();
    } finally {
    if (wc != null) {
    wc.close();
    public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
    final Blob blob = rs.getBlob(names[0]);
    return blob != null ? blob.getBytes(1, (int) blob.length()) : null;
    public Object deepCopy(Object value) {
    if (value == null)
    return null;
    byte[] bytes = (byte[]) value;
    byte[] result = new byte[bytes.length];
    System.arraycopy(bytes, 0, result, 0, bytes.length);
    return result;
    public boolean isMutable() {
    return true;
    public Object assemble(Serializable arg0, Object arg1) throws HibernateException {
    return assemble(arg0, arg1);
    public Serializable disassemble(Object arg0) throws HibernateException {
    return disassemble(arg0);
    public int hashCode(Object arg0) throws HibernateException {
    return hashCode();
    public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException {
    return replace(arg0, arg1, arg2);
    =================================================================
    can anyone give me the source code for this BinaryBlobType.java according to mysql blob handling ..

    Moderator action: crosspost deleted.

  • Java6, tomcat6, ojdbc6.jar and hibernate 3.3

    We were running an application with Oracle 10g, tomcat5 and java5 with ojdbc5.jar and hibernate 3 without any issues. We recently upgraded to java6, tomcat6, ojdbc6.jar and hibernate 3.3. We created a new instance of the Oracle10g database. We are now seeing intermittent errors at least once a week. The errors are:
    [ WARN] 12/11 09:52:02 (JCLLoggerAdapter:warn:357)-SQL Error: 17447, SQLState: 99999
    [ERROR] 12/11 09:52:02 (JCLLoggerAdapter:error:454)-OALL8 is in an inconsistent state
    With the following causes:
    Caused by: java.sql.SQLException: Protocol violation
    at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
    at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:199)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:263)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:271)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:445)
    at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:1053)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:194)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:791)
    at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:866)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1186)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3387)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3431)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1491)
    at org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:93)
    at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:1812)
    at org.hibernate.loader.Loader.doQuery(Loader.java:697)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
    at org.hibernate.loader.Loader.doList(Loader.java:2232)
    and
    java.sql.SQLException: Bigger type length than Maximum
    at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
    at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:199)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:263)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:271)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:445)
    at oracle.jdbc.driver.T4CMAREngine.buffer2Value(T4CMAREngine.java:2253)
    at oracle.jdbc.driver.T4CMAREngine.unmarshalUB2(T4CMAREngine.java:1101)
    at oracle.jdbc.driver.T4CTTIoer.unmarshal(T4CTTIoer.java:248)
    at oracle.jdbc.driver.T4C7Ocommoncall.receive(T4C7Ocommoncall.java:115)
    at oracle.jdbc.driver.T4CConnection.doCommit(T4CConnection.java:539)
    at oracle.jdbc.driver.PhysicalConnection.commit(PhysicalConnection.java:3432)
    at oracle.jdbc.driver.PhysicalConnection.commit(PhysicalConnection.java:3438)
    at org.apache.tomcat.dbcp.dbcp.DelegatingConnection.commit(DelegatingConnection.java:301)
    at org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.commit(PoolingDataSource.java:200)
    at org.hibernate.transaction.JDBCTransaction.commitAndResetAutoCommit(JDBCTransaction.java:170)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:146)
    and
    Caused by: java.sql.SQLException: OALL8 is in an inconsistent state
    at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
    at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:199)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:263)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:271)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:445)
    at oracle.jdbc.driver.T4C8Oall.marshal(T4C8Oall.java:474)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:180)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:791)
    at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:866)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1186)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3387)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3431)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1491)
    at org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:93)
    at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:1812)
    at org.hibernate.loader.Loader.doQuery(Loader.java:697)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
    at org.hibernate.loader.Loader.doList(Loader.java:2232)
    The errors occur when the user is querying for a list of objects. It does not seem to matter which list or type of objects. Attempting to recreate the error has not been fruitful - the queries are typical and ordinary routine data pulls. In the forums we see a lot posts about compatibility between drivers. The oracle 10g is using the ojdbc14.jar in its lib. Do we need to update this? Can we run java 6 against the 10g instance reliably?
    We have also seen a similiar issue occur once when the user tried a normal save:
    [ WARN] 12/11 10:00:11 (JCLLoggerAdapter:warn:357)-SQL Error: 17447, SQLState: 99999
    [ERROR] 12/11 10:00:11 (JCLLoggerAdapter:error:454)-OALL8 is in an inconsistent state
    [ERROR] 12/11 10:00:11 (OwnerHolder:doSave:787)-Problem occurred trying to prepare the info for save
    org.hibernate.exception.GenericJDBCException: could not get next sequence value
    at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:126)
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:114)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.id.SequenceGenerator.generate(SequenceGenerator.java:119)
    at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:122)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:117)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
    at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:535)
    at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:527)
    at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:523)
    at us.ca.santaclara.co.tax.tcas.dao.ParentDao.save(ParentDao.java:56)
    Caused by: java.sql.SQLException: OALL8 is in an inconsistent state
    at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
    at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:199)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:263)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:271)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:445)
    at oracle.jdbc.driver.T4C8Oall.marshal(T4C8Oall.java:474)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:180)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:791)
    at oracle.jdbc.driver.T4CPreparedStatement.executeMaybeDescribe(T4CPreparedStatement.java:866)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1186)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3387)
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3431)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1491)
    at org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:93)
    at org.hibernate.id.SequenceGenerator.generate(SequenceGenerator.java:98)
    [ERROR] 12/11 10:00:11 (JCLLoggerAdapter:error:532)-JDBC commit failed
    java.sql.SQLException: Protocol violation
    at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
    at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:199)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:263)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:271)
    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:445)
    at oracle.jdbc.driver.T4C7Ocommoncall.receive(T4C7Ocommoncall.java:130)
    at oracle.jdbc.driver.T4CConnection.doCommit(T4CConnection.java:539)
    at oracle.jdbc.driver.PhysicalConnection.commit(PhysicalConnection.java:3432)
    at oracle.jdbc.driver.PhysicalConnection.commit(PhysicalConnection.java:3438)
    at org.apache.tomcat.dbcp.dbcp.DelegatingConnection.commit(DelegatingConnection.java:301)
    at org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.commit(PoolingDataSource.java:200)
    at org.hibernate.transaction.JDBCTransaction.commitAndResetAutoCommit(JDBCTransaction.java:170)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:146)

    Thanks For the Post. It occurs mostly in my app too which uses oracle 10G with ojdbc14.jar , but client in weblogic 10.3 has ojdbc6.jar. My logic is , at that time network was impaired and oracle could not find exact cause of error. To replicate you can input severly in multiple threads same query to oracle so it cannot get timeout values or cannot serve incoming requests withing certain allowed timeframes. If you are using a RAC , it cannot SYNC those cache and memory dumps in GCS , PGA, and SGA, thus inconsistent state.

  • Integrate Crystal Reports with Spring MVC and Hibernate

    Hi all,
    having successfully used the JRC version 11.8.4.1094 in a Java environment with:
    1)JBoss 4.2.3,
    2)Oracle 11,
    3)EJB 2,
    4)Crystal Reports 2008,
    I would like to integrate Crystal Reports into my existing spring MVC and hibernate web app using:
    1)CRJ version 12.2.209,
    2)JBoss 5.1,
    3)Oracle 11,
    4)EJB 3,
    5)Crystal Reports 2008,
    reusing code integration. I used ReportExportControl and I produced the PDF directly.
    The error occurs when returning from EJB, into Delegate, and is the following:
    09:36:23,046 WARN  [InterceptorsFactory] EJBTHREE-1246: Do not use InterceptorsFactory with a ManagedObjectAdvisor, InterceptorRegistry should be used via the bean container
    09:36:23,062 WARN  [InterceptorsFactory] EJBTHREE-1246: Do not use InterceptorsFactory with a ManagedObjectAdvisor, InterceptorRegistry should be used via the bean container
    09:38:03,062 ERROR [[dispatcher]] Servlet.service() for servlet dispatcher threw exception
    java.lang.InstantiationException: com.crystaldecisions.sdk.occa.report.exportoptions.ReportExportFormat
         at java.lang.Class.newInstance0(Class.java:340)
         at java.lang.Class.newInstance(Class.java:308)
         at org.jboss.serial.classmetamodel.ClassMetaData.newInstance(ClassMetaData.java:334)
         at org.jboss.serial.persister.RegularObjectPersister.readData(RegularObjectPersister.java:239)
         at org.jboss.serial.objectmetamodel.ObjectDescriptorFactory.readObjectDescriptionFromStreaming(ObjectDescriptorFactory.java:412)
         at org.jboss.serial.objectmetamodel.ObjectDescriptorFactory.objectFromDescription(ObjectDescriptorFactory.java:82)
         at org.jboss.serial.objectmetamodel.DataContainer$DataContainerInput.readObject(DataContainer.java:845)
         at org.jboss.serial.persister.RegularObjectPersister.readSlotWithFields(RegularObjectPersister.java:353)
         at org.jboss.serial.persister.RegularObjectPersister.defaultRead(RegularObjectPersister.java:273)
         at org.jboss.serial.persister.RegularObjectPersister.readData(RegularObjectPersister.java:241)
         at org.jboss.serial.objectmetamodel.ObjectDescriptorFactory.readObjectDescriptionFromStreaming(ObjectDescriptorFactory.java:412)
         at org.jboss.serial.objectmetamodel.ObjectDescriptorFactory.objectFromDescription(ObjectDescriptorFactory.java:82)
         at org.jboss.serial.objectmetamodel.DataContainer$DataContainerInput.readObject(DataContainer.java:845)
         at org.jboss.serial.persister.RegularObjectPersister.readSlotWithFields(RegularObjectPersister.java:353)
         at org.jboss.serial.persister.RegularObjectPersister.defaultRead(RegularObjectPersister.java:273)
         at org.jboss.serial.persister.RegularObjectPersister.readData(RegularObjectPersister.java:241)
         at org.jboss.serial.objectmetamodel.ObjectDescriptorFactory.readObjectDescriptionFromStreaming(ObjectDescriptorFactory.java:412)
         at org.jboss.serial.objectmetamodel.ObjectDescriptorFactory.objectFromDescription(ObjectDescriptorFactory.java:82)
         at org.jboss.serial.objectmetamodel.DataContainer$DataContainerInput.readObject(DataContainer.java:845)
         at org.jboss.serial.io.MarshalledObjectForLocalCalls.get(MarshalledObjectForLocalCalls.java:60)
         at org.jboss.ejb3.remoting.IsLocalInterceptor.invokeLocal(IsLocalInterceptor.java:101)
         at org.jboss.ejb3.remoting.IsLocalInterceptor.invoke(IsLocalInterceptor.java:72)
         at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102)
         at org.jboss.aspects.remoting.PojiProxy.invoke(PojiProxy.java:62)
         at $Proxy286.invoke(Unknown Source)
         at org.jboss.ejb3.proxy.impl.handler.session.SessionProxyInvocationHandlerBase.invoke(SessionProxyInvocationHandlerBase.java:207)
         at org.jboss.ejb3.proxy.impl.handler.session.SessionProxyInvocationHandlerBase.invoke(SessionProxyInvocationHandlerBase.java:164)
         at $Proxy284.getXXXX(Unknown Source)
         at xx.xxx.xxxxxx.spring.manager.report.ReportManagerImpl.getXXXX(ReportManagerImpl.java:26)
         at xxx.xxxx.springprova.WelcomeController.handleRequestInternal(WelcomeController.java:70)
         at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
         at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
         at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
         at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
         at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
         at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
         at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
         at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
         at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
         at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
         at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
         at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
         at java.lang.Thread.run(Thread.java:662)
    Have an idea, please?
    Thank you.

    You'll need to install the Crystal .NET that comes with VS 2005. You then install Crystal XI R2 over the top and not only will Crystal be integrated with the IDE, it should use the updated assemblies from R2.
    -Dell
    - A computer only does what you told it to, not what you thought you told it to!</p>

  • Add Image to Jasper Report with Struts 2 and Hibernate

    Hi I want to add image to jasper report[pdf] in the environment of Struts 2 framework and hibernate. I am trying
    this for last couple of days, but i am unable to get the work done. if any body know the steps to add image to
    jasper reports, please help me or if u have any tutorials please let me know. I am using iReport-nb-3.5.0 to generate jasper files.
    Thanks in advance

    Finally i found a way to add image to jasper report. It is pretty simple, just give the exact image location to the image expression. In your web application, the image location may vary so, dynamically set the image location from your model class. Also, make sure that your lib folder contains itext-1.3.1.jar. If your lib folder contains itext-1.3.1.jar and iText-2.1.3.jar u will get like: java.lang.NoSuchMethodError: com.lowagie.text.Image.plainWidth()F
    So remove the iText-2.1.3.jar and keep only itext-1.3.1.jar, try this will work

  • Flex 1.5 and Hibernate 3

    Hi everyone,
    I am trying to make a sample application for the evaluation
    purpose. I have created some java beans and their corresponding
    actionscript classes. When I call any java method which returns an
    object say Student, it works fine. Flashgateway Servlet serializes
    Objects correctly and no exception occurs.
    But when try to do the same thing with Hibernate 3,
    Flashgateway Servlet cannot serialize object and throws Hibernate
    Lazy Initialization Exception.
    Can any one guide me or show me some sample of Flex 1.5 and
    Hibernate 3 .
    OR
    Help me to find what I am doing wrong .
    Any help would be appreciated .
    Thanks

    hey flex 2 beta is come out.. people dont work much with flex
    1.2 or flex 3,,, cause there is much difference in coding and
    syntax. so i recommend u start using the new version,,flex 2 beta 3
    , cause later it might cause problem..

  • [NewBie] Not able to connect JPA and Hibernate ?

    Hi,
    In last few days I have read some tutorial and started doing JPA and Hibernate tutorials. But I am not able to make it work. Can some one please point out what is that I am doing wrong? Here are the details of what I am doing
    I am using
    IDE : Eclipse EE Indigo
    Following jars
    antlr-2.7.6.jar
    commons-collections-3.2.jar
    dom4j-1.6.1.jar
    hibernate-annotations-3.4.0.GA.jar
    hibernate-commons-annotations-3.1.0.GA.jar
    hibernate-entitymanager-3.4.0.GA.jar
    hibernate-jpa-2.0-api.jar
    hibernate3-3.3.2.GA.jar
    javaee-api-5.0-3.jar
    javassist-3.9.0.GA.jar
    junit-4.8.2.jar
    log4j-1.2.12.jar
    slf4j-api-1.6.1.jar
    slf4j-simple-1.6.1.jar
    sqljdbc.jar => For connecting to MS SQL Server database
    junit-4.8.2 => For testing the application
    The target runtime is set as JBoss 5.0 with jars of JBoss 6.0
    Here is my persistence.xml. This file is under "src\META-INF"
    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
         <persistence-unit name="JH1" transaction-type="RESOURCE_LOCAL">
              <provider>org.hibernate.ejb.HibernatePersistence</provider>
              <class>entity.Users</class>
              <exclude-unlisted-classes>false</exclude-unlisted-classes>
              <properties>
                   <property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
                   <property name="hibernate.show_sql" value="true"/>
                   <property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://localhost:1433;databaseName=TempEPMUser"/>
                   <property name="javax.persistence.jdbc.user" value="user"/>
                   <property name="javax.persistence.jdbc.password" value="password"/>
                   <property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
                   <property name="javax.persistence.transactionType" value="RESOURCE_LOCAL"/>
              </properties>
         </persistence-unit>
    </persistence>
    Here is the Users.java code. This is the entity class created using the context menu item JPA Entities from tables
    package entity;
    import java.io.Serializable;
    import javax.persistence.*;
    import java.sql.Timestamp;
    import java.math.BigDecimal;
    * The persistent class for the Users database table.
    @Entity
    public class Users implements Serializable { 
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="Usr_UserID")
    private long usr_UserID;
    @Column(name="Usr_DeptId")
    private BigDecimal usr_DeptId;
    public Users() { 
    public long getUsr_UserID() { 
    return this.usr_UserID;
    public void setUsr_UserID(long usr_UserID) { 
    this.usr_UserID = usr_UserID;
    Here is the testing code TestUser.java
    package testentity;
    import java.util.List;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.EntityTransaction;
    import javax.persistence.Persistence;
    import javax.persistence.PersistenceException;
    import org.apache.log4j.BasicConfigurator;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import entity.Users;
    public class TestUser {
         private EntityManagerFactory emf;
         private EntityManager em;
         @Before
         public void initEmfAndEm(){
              BasicConfigurator.configure();
              try {
                   emf = Persistence.createEntityManagerFactory("JH1");
              } catch (PersistenceException pe) {
                   System.out.println(pe.getMessage());
              em = emf.createEntityManager();
         @After
         public void cleanup() {
              em.close();
         @Test
         public void emptyTest() {
              EntityTransaction et = em.getTransaction();
              et.begin();
              @SuppressWarnings("unchecked")
              final List<Users> listUser = em.createQuery("select usr_DeptID from Users").getResultList();
              et.commit();
              for (Users usr: listUser){
                   int depid = usr.getUsr_DeptId().intValue();
                   System.out.println("User Department id is "+depid);
    When I execute the code I get following error message
    java.lang.UnsupportedOperationException: The user must supply a JDBC connection
    at org.hibernate.connection.UserSuppliedConnectionProvider.getConnection(UserSuppliedConnectionProvider.java:54)
    at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
    at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
    at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:142)
    at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:85)
    at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1354)
    at org.hibernate.ejb.TransactionImpl.begin(TransactionImpl.java:38)
    at testentity.TestUser.emptyTest(TestUser.java:42)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
    at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

    Hi,
    Try following the JPA tutorials for WebLogic, JPA using EclipseLink or Hibernate will be the same if you stick to the specification. WebLogic 10.3.4.0 ships with a Java EE 6 compliant JPA 2.0 implementation in EclipseLink - you may want to give that a try.
    http://wiki.eclipse.org/EclipseLink/Examples/JPA/WebLogic_Web_Tutorial
    http://wiki.eclipse.org/EclipseLink/Examples/Distributed
    I also have a JBoss 6 tutorial for getting JPA working as well.
    BTW, your persistence unit is currently application managed - try switching to container managed - then most of your jar dependencies will go away as everything is already setup for you to do dependency injection via the container.
    http://wiki.eclipse.org/EclipseLink/Examples/JPA/JBoss_Web_Tutorial
    thank you
    Michael O'Brien
    http://www.eclipselink.org

  • Training material on JSF, Spring and Hibernate

    Hi All,
    I'm new to JSF. I need some good training material on JSF, Spring and Hibernate.
    I've tried lot many tutorials online, but cannot find a real good one.
    Also I need to learn how we can integrate together JSF, Spring and Hibernate to build web applications.
    Thanks
    Payal

    As far as documentation vs examples, that depends on the individual.
    The Spring documentation is quite large, but Spring itself is very modular. So you can pretty much get away with reading the pieces you need when you need them and ignoring the rest.
    Start with inversion of control until you feel you understand the concept. At its core, the idea is simple. Suppose you have a business class, FooService, and it needs to utilize BarService to implement its business logic. The non-Spring way would be to have the FooService class be responsible for getting an instance of BarService. The Spring way is for FooService to have a setter to be given an instance of BarService:
    public class FooServiceImpl implements FooService
        private BarService barService;
        public void setBarService(BarService barService) { this.barService = barService; }
    }Then the Spring container is used to "wire together" the instances:
    <beans>
        <bean id="barService" class="BarServiceImpl" />
        <bean id="fooService" class="FooServiceImpl">
            <property name="barService" ref="barService" />
        </bean>
    </beans>Note the advantage when using the classes in different contexts, e.g. unit testing vs production.
    If I were you, I would take the sample app you have already done with JSF and try to integrate Spring into it. Move all the business logic into beans in the Spring container while keeping the view logic in the JSF layer.

Maybe you are looking for