Perist not throwing exception

Hi everyone,
I am new to JPA, and currently trying to persist/update an entity to a HSQL database. According to the API, the persist method of the class EntityManager, throws an exception if we try to persist an entity which already exists, but in my case, it seems to update the entity, if it exists.
Here's a snippet of the commit code
public void commit(Object obj){
        if(entityManager == null) {
            entityManager = getEmf().createEntityManager();
        if(entityTransaction == null){
            entityTransaction = entityManager.getTransaction();
        if(!entityTransaction.isActive()){
            entityTransaction.begin();
        entityManager.persist(obj);
        try{
            entityTransaction.commit();
        } finally {
            close();
private void close(){
        EntityManager tempEntityManager = entityManager;
        EntityTransaction tempEntityTransaction = entityTransaction;
        entityManager = null;
        entityTransaction = null;
        try{
            if(tempEntityTransaction != null &&  tempEntityTransaction.isActive()){
                tempEntityTransaction.rollback();
        } finally{
            if(tempEntityManager != null) {
                tempEntityManager.close();
    }As you can see, my commit method calls the persist method always, so if I try to commit an entity twice, it should throw an exception, but instead it updates the entity. Could any of you tell me why this is the case?

Look at the setLenient method.
Also, read the part in the docs about when the number of characters does and does not matter when parsing.

Similar Messages

  • EJB is not throwing exception to calling Action class in Unix environment

    Hi
    We are using Weblogic Server 9.2.3.0.
    One of our EJB is not throwing exception to calling Action class in Unix environment. Its working fine in Windows.
    Somehow the EJB is swallowing the exception.
    any idea? I suspect it may be environmental issue?
    thank you

    Hi
    We are using Weblogic Server 9.2.3.0.
    One of our EJB is not throwing exception to calling Action class in Unix environment. Its working fine in Windows.
    Somehow the EJB is swallowing the exception.
    any idea? I suspect it may be environmental issue?
    thank you

  • Java Does Not Throw Exception When Writing To Read-Only Files

    I have noticed that when I try to write to a read-only file in a window environment, Java does not throw an IOExcpetion, it just dosn't write to the file.
    I am writing an FTP server and here is the code:
         public static long copyStream(InputStream in, OutputStream out)throws IOException
              IOException exception = null;
              long copied = 0;
              try
                   byte buffer[] = new byte[1024];
                   int read;
                   while((read = in.read(buffer)) != -1)
                        out.write(buffer, 0, read);
                        copied += read;
              catch(IOException e)
                   //ensures that the streams are closed.
                   exception = e;
              try
                   in.close();//ensures output stream gets closed, even if there is an
                   //excption here.
              catch(IOException e){exception = e;}
              out.close();//try to close output.
              if(exception != null)
                   //exception is not null, an exception has occured.
                   //rethrow exception.
                   throw exception;
              return copied;//all ok, return bytes copied.
         }Is this a bug in JAVA VM? Is so, how should I report it?

    I have noticed that when I try to write to a read-only file in a window environment,
    Java does not throw an IOExcpetion, it just dosn't write to the file.C:\source\java\Markov>attrib readonly.out
    A R C:\source\java\Markov\readonly.out
    �C:\source\java\Markov>java b
    java.io.FileNotFoundException: readonly.out (Access is denied)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at b.main(b.java:5)
    import java.io.*;
    public class b {
        public static void main(String[] args) {
         try     {
              OutputStream os = new FileOutputStream ( "readonly.out");
         catch (Exception e) {
              e.printStackTrace();
    }

  • One-way soap call do not throw exception

    Hello,
    I prepared a client for web service with JWSDP-2.0. wscompile generated proxy classes. The web service uses "basic authentication". Now comes my problem. wscompile generated stub which calls
    _sendOneWay((java.lang.String) _getProperty(ENDPOINT_ADDRESS_PROPERTY), _state);Because the web service is defined as: void ENCRYPTED_MESSAGE(SOAPElement)
    When basic authentication fails (I get HTTP 401 code - which I can see in debug created by JVM parameter -Djavax.net.debug=all ) then NO EXCEPTION is fired!!!
    When I change the wsdl and add dummy output parameter, then send((java.lang.String) getProperty(EN... is generated and authentication fires exception. But this is not the right way to do it.
    My question is - can I make wscompile to generate Stub without _sendOneWay?
    Thanks for yout time and attention!
    Honza

    I forgot to say that I am using JDeveloper 9.0.5.2 and that I have built an ADF application with Struts + ADF Business Components (bc4j)
    Thanks

  • Exception not throwing to action class in Unix environment

    Hi
    We are using Weblogic Server 9.2.3.0.
    One of our EJB is not throwing exception to calling Action class in Unix environment. Its working fine in Windows.
    Somehow the EJB is swallowing the exception.
    any idea? I suspect it may be environmental issue?
    thank you

    Thanx for your reply.. I just found a solution and would like to share that with you. There are some default request parameters passed by the portal to the action class. "strutsAction" is one of them. If you print this parameters, you will see that it contains the complete url of your action. Now you can use String manipulation to extract the value of the parameters.
    I know its a crude solution. But it works fine.
    Best regards,
    Omer

  • Web part throwing exception at run time but not in debug mode

    The below code is throwing exception at run time but does not throw exception while debugging in Visual Studio. This is really causing difficulty for me to detect the cause of exception. Below I have also placed the exception image for reference.
    namespace CheckforContractorLogin.VisualWebPart1
    public partial class VisualWebPart1UserControl : UserControl
    protected void Page_Load(object sender, EventArgs e)
    if (!IsPostBack)
    string loginName = string.Empty;
    string coc_url = string.Empty;
    SPQuery spQuery = new SPQuery();
    spQuery.Query = "<Where><Eq><FieldRef Name='LoginName' /><Value Type='Text'>" + currentUser + "</Value></Eq></Where>";
    Guid _spSiteID = SPContext.Current.Site.ID;
    Guid _spWebID = SPContext.Current.Site.OpenWeb().ID;
    SPSecurity.RunWithElevatedPrivileges(delegate()
    using (SPSite _spSite = new SPSite(_spSiteID))
    using (SPWeb _spWeb = _spSite.OpenWeb(_spWebID))
    //if user has already accepted the COC
    SPList getSPList = _spWeb.Lists["RedirectUrl"];
    SPListItemCollection getspItemColl = getSPList.Items;
    foreach (SPListItem item in getspItemColl)
    if (Convert.ToString(item["Title"]) == "Policy Acceptance")
    coc_url = Convert.ToString(item["Url"]);
    SPList spList = _spWeb.Lists["Policy Acceptance Status"];
    SPListItemCollection spItemColl = spList.GetItems(spQuery);
    bool result = getADUserInfo();
    if ((spItemColl.Count == 0) && (result))
    Response.Redirect(coc_url);
    protected string currentUser
    get
    string currentUser1 = HttpContext.Current.User.Identity.ToString();
    int index = currentUser1.IndexOf("\\") + 1;
    string currentLoginUser = currentUser1.Substring(index);
    return currentLoginUser;
    protected bool getADUserInfo()
    DirectoryEntry dentry = null;
    DirectorySearcher dsearcher = null;
    string ldap = string.Empty;
    string empID = string.Empty;
    string _empID = string.Empty;
    try
    Guid spSiteGUID = SPContext.Current.Site.ID;
    Guid spWebGUID = SPContext.Current.Site.OpenWeb().ID;
    SPSecurity.RunWithElevatedPrivileges(delegate()
    using (SPSite elevatedSiteColl = new SPSite(spSiteGUID))
    using (SPWeb elevatedWeb = elevatedSiteColl.OpenWeb(spWebGUID))
    SPList spList = elevatedWeb.Lists["LDAP_Paths"];
    SPQuery spQuery = new SPQuery();
    spQuery.Query = "<Where><Eq><FieldRef Name='OU'/>"
    + "<Value Type='Text'>QD</Value></Eq></Where>";
    SPListItem spItem = spList.GetItemById(1);
    ldap = spItem["Path"].ToString();
    dentry = new DirectoryEntry();
    dentry.Path = ldap;
    dentry.Username = "******\\sp_admin";
    dentry.Password = "******";
    dsearcher = new DirectorySearcher(dentry);
    dsearcher.Filter = String.Format("(&(ObjectCategory=Person)(sAMAccountName=" + currentUser + "))");
    SearchResult searchResult = dsearcher.FindOne();
    dentry = searchResult.GetDirectoryEntry();
    if (searchResult != null)
    if (dentry.Properties.Contains("physicalDeliveryOfficeName"))
    empID = dentry.Properties["physicalDeliveryOfficeName"][0].ToString();
    if (empID.Contains("QA-"))
    return true;
    else
    return false;
    catch (Exception e)
    throw e;
    finally
    dentry.Close();
    dentry.Dispose();
    dsearcher.Dispose();

    Hi Zakir,
    I am not sure but it would be nice if you can do following
    Try search ULS log with correlation id and find exact error and share here. If not able to find do following
    Or in catch block write
    Response.Write(ex.ToString());
    and check what exception its giving.

  • Constructor can throw exception or Not ?

    Anybody please tell me if the constructor throws an exception or not ?
    Please reply soon
    Thanks
    Amitindia

    A constructor can throw an Exception. However I
    would suggest throwing the generic Throwable, Error,
    Exception or RuntimeException rather than a specific
    exception is bad practice and you should choose an
    appropirate exception to throw.All depends on wich kind of exception you are throwing,checked or unchecked. It's an even worse form to throw a RE, Error, or Throwable when you are throwing in fact a checked exception.
    Nevertheless, I do agree, you must always strive to not throw exceptions, of any kind, in your construtor code. Construtors should be simple and reliable. Unles you have a very compelling reason to not do it, try to isolate the risky parts of the code where they are called ofter object construction or class loading.
    May the code be with you.

  • Dispatching GridSelectionEvent throw exception at runtime - A build issue with FB 4.5

    This is a strang probelm I am facing with.
    My code dispatches GridSelectionEvent after setting girds' selected item in one logic path. Following is code lines -
    myDataGrid.selectedItem = instanceTag;
    myDataGrid.dispatchEvent(new GridSelectionEvent(GridSelectionEvent.SELECTION_CHANGE));
    Flash player throws following error on above statements encounter -
    TypeError: Error #1009: Cannot access a property or method of a null object reference.
        at spark.accessibility::DataGridAccImpl/eventHandler()
        at flash.events::EventDispatcher/dispatchEventFunction()
        at flash.events::EventDispatcher/dispatchEvent()
        at mx.core::UIComponent/dispatchEvent()
    I am saying it is a strang for me because when I use swf file generated by Flex Builder (4.5)'s export to release build, it does not throw error and code works fine as expected.
    But, when I user swf file generated by Ant script, I face the above issue.
    The Flex builder settings is as shown in following image -
    Ant  mxmlc script is as follow -
    <mxmlc      
               file="${basedir}/src/AppMonConfigWizard.mxml"
                static-rsls="false"
               keep-generated-actionscript="false"
               output="${basedir}/bin-release/AppMonConfigWizard.swf" >
         <locale>en_US</locale>
          <load-config filename="${FLEX_HOME}/frameworks/flex-config.xml"/>
          <source-path path-element="${FLEX_HOME}/frameworks"/>
          <source-path path-element="${basedir}/src/locale/{locale}"></source-path>
          <compiler.library-path file="${basedir}/../wizard_framework/bin/wizard_framework.swc" append="true"/>
         <compiler.library-path file="${basedir}/../../utils/bin/utils.swc" append="true"/>
          <include-resource-bundles>ErrorMessages</include-resource-bundles>
          <include-resource-bundles>Strings</include-resource-bundles>
    </mxmlc>
    As mentioned earlier that following statements cause exception -
         myDataGrid.selectedItem = instanceTag;
         myDataGrid.dispatchEvent(new GridSelectionEvent(GridSelectionEvent.SELECTION_CHANGE));
    If I change it to
         myDataGrid.setSelectedIndex(<some index value>)   /*selectedItem replaced with setSelectedIndex*/
         myDataGrid.dispatchEvent(new GridSelectionEvent(GridSelectionEvent.SELECTION_CHANGE));
    it does not throw exception.  I would like to mention that myDataGrid.selectedItem = instanceTag; does sets the selected item but then in that case issue arises when dispatching event.
    I my application, similar statemetns were lot at many places (as there were no such issue with SDK 3.1 which was using earlier) so instead of making changes there, it would be better to imitate the build that Flex builder uses when exported the release build.
    Thanks in advance,
    Prithveesingh Zankat.

    Solved it: had set the only public surface contracts checkbox by mistake and the cosntructor was protected...
    Luis Abreu

  • Exceptions - documentation on which methods throw exceptions ?

    Hi, does anyone know where I can find full documentation on iphone SDK methods
    The iphone SDK documentation seems to be incomplete.
    For instance, the discussion section of the SDK documentation for NSMutableArray addObject method doesn't mention anything about exceptions.
    However, the method could throw an exception (and this is mentioned in http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMu tableArray_Class/Reference/Reference.html)
    I'm assuming that alloc will not throw exceptions and that it will just return nil if no memory is available. However, I haven't found any documentation that states this.
    Does anyone have a pointer to Apple documentation for methods (that includes information on any (and all) exceptions thrown by the method and also includes information on possible return values for the method) ?

    There is this
    http://java.sun.com/products/jdbc/driverdevs.html
    I am pretty sure that there is little in the meta data stuff that has to be supported.

  • Persist does not throw any exception in a JUnit test

    I am implementing a JUnit test using Toplink as JPA provider. I must be missing something because I try to persist two times the same entity and no exception is thrown. Neither PersistenceException nor any other type of exception. The code cannot be easier:
    @Test
    public void testAddExistingTeam() throws Exception {
    Team team = new Team("team2");
    try{     
    EntityManagerFactory emf =
    Persistence.createEntityManagerFactory("fofo");
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    em.persist(team);
    em.persist(team);
    em.getTransaction().commit();
    em.close();
    catch(Exception e){
    e.printStackTrace();
    Notice the two em.persist(team).
    This code does not seem to either enter the catch block or produce any sort of exception. On the other hand, I have checked that after the first
    em.persist(team); the team is really managed.
    The relevant parts of the Team class definition follow:
    @Entity
    @Table (name ="TEAM")
    public class Team implements Serializable {
    @Id
    @Column (name="NAME")
    private String name;
    @ManyToOne
    @JoinColumn (name="CLUB_NAME", referencedColumnName="NAME")
    private Club club;
    private Category category;
    private String email;
    @ManyToMany(mappedBy="teams")
    private List<Competition> competitions;
    public Team (String name){
    this.name = name;
    this.club = null;
    this.competitions = new ArrayList<Competition>();
    ....getters/setters....and more constructors.
    I am really puzzled by this issue. Somebody could help??? I would be really grateful!!!
    Josepma

    This is expected behavior as persist is a no-op if called on a managed entity (other than to cascade over relationships marked with cascade.Persist), and the first persist call makes the passed in team entity managed.
    Try calling em.flush(); and em.clear(); between the persist calls to get an exception.
    The first flush will ensure the team is inserted in the database, while clear will detach it so that the second persist call will try to insert the team. JPA providers are not required to throw the entityExistsException on persist - it can be delayed until the transaction is flushed or committed, so you are likely to get a PersistenceException from the commit instead of EntityExistsException from persist.
    Best Regards,
    Chris

  • Impersonate domain user to call MessageQueue.Create() to create a private queue throw exception "Msmq service is not available".

    The code impersonate a domain user to create a private messaging queue on local machine, using MessageQueue.Create(".\\myqueue").
    When the current user is a member of local administrators, it works well. 
    When the current user is a member of local users, it throw exception "Msmq service is not available."

    Hi Psun,
    In my opinion, this thread is related to MSMQ forum. So please post thread on that forum for more effective response. Thank you for understanding. Please refer to the following link.
    http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/home?forum=msmq
    Regards,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • LookupXRef not throwing any exception

    Hi All,
    We are using ESB Cross referencing out of box functionality provided with 10.1.3.3 SOA Suite.We have a case where we need to have some busineess logic when the value we are trying to look up in the Cross Ref table doesnot exists , in that case we tried to use needAnException(set to true()) field in the lookupXRef function inside the transformation.However its not throwing any exception in the BPEL Process.Instead it is avoiding other fields in getting populated underneath it in that complex type.As a result we are losing important business data inside the BPEL Process.Same is the case for PopulateXRefRow function as well while we are trying to insert a duplicate value into the Cross referencing table from BPEL Process.
    We need an exception for the above two cases.Are there any work arounds for these.
    We are in an urgent need of it.Can any one help us?
    Regards,
    Venkat.

    hi,
    after using XREFTOOL to create my cross referencing:
    D:\productORACLE\10.1.3.1\SOA\Oracle_1\integration\esb\bin>xreftool.bat -shell
    listTablesTotal number of xref tables: "1"
    No. TableName
    1. MONREF
    listColumns MONREFTotal number of columns for xref table "MONREF" : "2"
    No. ColumnName
    1. SAP
    2. SIEBEL
    >
    i try to use (after a reboot of soa suite), xpath function xref:populateXRefRow inside a assign task of my bpel 10.1.3.3.
    i have the following exception :
    Message handle error.
    An exception occurred while attempting to process the message "com.collaxa.cube.engine.dispatch.message.invoke.InvokeInstanceMessage"; the exception is: XPath expression failed to execute.
    Error while processing xpath expression, the expression is "xref:populateXRefRow('monref','sap','123','siebel','2','ADD')", the reason is FOTY0001: type error.
    Please verify the xpath query.
    ORABPEL-05002
    Message handle error.
    An exception occurred while attempting to process the message "com.collaxa.cube.engine.dispatch.message.invoke.InvokeInstanceMessage"; the exception is: XPath expression failed to execute.
    Error while processing xpath expression, the expression is "xref:populateXRefRow('monref','sap','123','siebel','2','ADD')", the reason is FOTY0001: type error.
    Please verify the xpath query.
    at com.collaxa.cube.engine.dispatch.DispatchHelper.handleMessage(DispatchHelper.java:171)
    at com.collaxa.cube.engine.dispatch.BaseScheduledWorker.process(BaseScheduledWorker.java:70)
    at com.collaxa.cube.engine.ejb.impl.WorkerBean.onMessage(WorkerBean.java:86)
    at sun.reflect.GeneratedMethodAccessor48.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at com.evermind.server.ejb.interceptor.joinpoint.EJBJoinPointImpl.invoke(EJBJoinPointImpl.java:35)
    at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:119)
    at com.evermind.server.ejb.interceptor.system.DMSInterceptor.invoke(DMSInterceptor.java:52)
    Is there a solution or did i miss something ??
    i try to use the same xpath function inside a ESB project (xslt transformation)
    <xsl:value-of select='xref:populateXRefRow("MONREF","SAP",/tns:name,"SIEBEL",ora:generateGUID(),"ADD")'/>
    and i've got the error message :
    XML-22016: (Error) Extension function namespace should start with 'http://www.oracle.com/XSL/Transform/java/'.

  • Why Overridden method do not throw Broder exception

    Why Overridden method of derived class do not throw Broder exception than the method that is in base class

    Why Overridden method of derived class do not throw
    Broder exception than the method that is in base classWhat is a Broder Exception?
    I don't understand your question?
    You are asking something about overriding a method:
    http://java.sun.com/docs/books/tutorial/java/IandI/override.html

  • Javax.servlet.Filter, throw file not found exception

    I want to use a url which is not exists to let the filter run.
    In the method doFIlter(), if the URL is this one, I will return and do not run chain.doFilter
    Why throw FIle not found exception? Will the fileter check the url whether exist or not?

    I use the URL to let the filter run, but do not want to go to the URL.What should happen if someone requests the URL from the server ?
    Nothing is not possible.
    One possibilty is to send the HTTP Response Code 204 - No Content
    The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.
    If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent's active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent's active view.
    The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.
    (RFC 2616 Fielding, et al.)

  • OracleConnection.ClearAllPools() throws exception Operation not valid due t

    My app allows new logons so during the app startup I call my general "new logon" procedure that among other things does a ClearAllPools.
    OracleConnection.ClearAllPools() throws exception "Operation not valid due to current state of the object".
    I have converted from
    System.Data.OracleClient.OracleConnection
    to
    Oracle.DataAccess.Client.OracleConnection
    Did not have any problem when using the former.

    According to the documentation, ClearAllPools() throws an exception if there's no connection pool to clear. Most likely in that case the System.Data.OracleClient version is just not doing anything instead.
    You should just be able to catch InvalidOperationException() at that point and ignore it.

Maybe you are looking for

  • Can Pages Create Forms?

    In other word processors (Open Office 2.2, to be precise - and probably word, but I don't use it so I don't know) you can create a form that can be edited by whoever reads your document - ie, you can create something like: First Name: Last Name: Occu

  • Wallpaper disappears when I bring up Photobooth from my Apps?

    I'm trying to figure out how to fix this glitch I've been experiencing recently with my Wallpaper/background. Whenever I bring up Photo Booth from my applications, my wallpaper disappears to be replaced by a solid blue background. It's only started h

  • Poor pax implementation help.

    I have a dead system due to 10.4.6 failing mysteriously. I'd like to get my system back, and as apple don't want to help users, maybe someone here can answer a few questions, which might help. Before going to work, I set SU to downaload and install t

  • HDMI Splitter   360/ATV/CableBox

    I was looking for an HDMI Splitter online.  I know that the max speed of HDMI is 10gbps, and most splitters I'm finding, (3 way splitter) are 2.5gbps. Is 2.5gbps still enough to have full quality for an Xbox 360 (and possibly whatever the next xbox w

  • Bugs in macromedia products

    just recently i noticed that when using flash and dreamweaver that the fonts used in the interface have changed, icons and text dont show up on or next to buttons, and the properties panel doesnt refresh correctly when switching between objects on th