Friday, May 6, 2011

Configure Hibernate to use Oracle's SYS_GUID() for Primary Key

I am looking for a way to get hibernate to use oracle's SYS_GUID() function when inserting new rows. Currently my DB tables have SYS_GUID() as the default so if hibernate simply generated SQL that omited the value it should work.

I have everything working, but it is currently generating the UUID/GUID in code using the system-uuid generator:

@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
@Column(name = "PRODUCT_ID", unique = true, nullable = false)
public String getId() {
    return this.productId;
}

This is fine, but I would prefer that the guids were generated by the database so they will be sequential and potentially have better performance. Plus I would just like to know how to configure this.

I am using annotations for configuration, but xml configuration examples are awesome as well.

Here is a sample table definition (in case it matters):

CREATE TABLE SCHEMA_NAME.PRODUCT
(
    PRODUCT_ID RAW(16) DEFAULT SYS_GUID() NOT NULL,
    PRODUCT_CODE VARCHAR2(10 CHAR) NOT NULL,
    PRODUCT_NAME VARCHAR2(30 CHAR) NOT NULL,
    PRODUCT_DESC VARCHAR2(512 CHAR)
)

UPDATE:

Mat's sollution of using "guid" worked, here is the sql generated:

Hibernate: 
    select rawtohex(sys_guid()) 
    from dual
Hibernate: 
    insert into PRODUCT
    (PRODUCT_CODE, PRODUCT_DESC, LOB_ID, PRODUCT_NAME, PROVIDER_ID, PRODUCT_ID) 
    values (?, ?, ?, ?, ?, ?)


It seems that using the columns default value in an insert is not possible, so the choice is between an application generated guid and a database round trip.

From stackoverflow
  • I think you can do it by setting the generator to native. I'm not really sure how to do it in Hibernate but in NHibernate you'd do something like this in the XML:

    <id column="PRODUCT_ID">
      <generator class="native"/>
    </id>
    
    Adeel Ansari : "native" is sequence in Oracle. Therefore, I doubt it. But trying it out is not a bad idea.
    Adeel Ansari : By the way, you specified that you do this in NHibernate, but didn't specify the database and thats the primary much concern here.
    cdmckay : There's a very good chance I'm wrong, I've just started to use NHibernate.
  • Hi Ryan. You might be able to use the "guid" generator. See this post from the Hibernate forum. It looks like they added support for Oracle using SYS_GUID() a while back, but the documentation still says they only support SQL Server and MySQL.

    I haven't worked with JPA annotations yet, but here is an example using XML configuration:

    <id name="PRODUCT_ID">
      <generator class="guid" />
    </id>
    

    EDIT: In regards to your second question, I think you are asking why Hibernate can't do something like this:

    INSERT INTO PRODUCT (PRODUCT_ID, /* etc */)
    SELECT SYSGUID(), /* etc */
    

    The reason is that Hibernate must know what the object's ID is. For example, consider the following scenario:

    1. You create a new Product object and save it. Oracle assigns the ID.
    2. You detach the Product from the Hibernate session.
    3. You later re-attach it and make some changes.
    4. You now want to persist those changes.

    Without knowing the ID, Hibernate can't do this. It needs the ID in order to issue the UPDATE statement. So the implementation of org.hibernate.id.GUIDGenerator has to generate the ID beforehand, and then later on re-use it in the INSERT statement.

    This is the same reason why Hibernate cannot do any batching if you use a database-generated ID (including auto-increment on databases that support it). Using one of the hilo generators, or some other Hibernate-generated ID mechanism, is the only way to get good performance when inserting lots of objects at once.

    Ryan Cook : This worked but produced some extra sql, see my update. Thanks for your time.
    Matt Solnit : Hi Ryan. I edited my answer to try to respond to your follow-up question.
    Ryan Cook : FYI: Doing this via annotation is simple: @GenericGenerator(name = "guid", strategy = "guid")

Renaming XML nodes using E4X in AS3

I have an XML object in AS3 that is formatted as follows:

<data>
  <nodes>
    <item></item>
    <item></item>
    ...
  </nodes>
  <nodes>
    <item></item>
    <item></item>
    ...
  </nodes>
  ...
</data>

My problem is I want to rename the node names("nodes" and "item") to something more relevant e.g. "nodes" could be "author", and "item" could be "book".

So what would be the best way to do this with E4X in AS3?

From stackoverflow
  • Hi,

    As far as I know there is no way to do this natively within ActionScript, however here is a simple function that will accomplish just that. First I am converting it to a string, then using a simple regular expression to find and replace all instances.

    function replaceAll(findTag:String, replaceWith:String, source:XML):XML
     {
      var xmls:String = source.toXMLString();
      var findPattern:RegExp = new RegExp(findTag, "g");
      xmls = xmls.replace(findPattern, replaceWith);
      return new XML(xmls);
     }
    

    Hope it helps.

  • you can use the setName() method of XML Object in AS3.

    example:

       //extract all nodes named "nodes"
    
        var l:XMLList=data..nodes;
        for each(var n:XML in l){
           n.setName("new_node_name");
        }
    
        //extract all nodes named "item"
    
        var l2:XMLList=data..item;
        for each(var n2:XML in l2){
           n2.setName("new_item_name");
        }
    
    TandemAdam : I was hoping there would be something like: data..nodes.setName("new_node_name"); But that would be asking too much. Thanks!

How to select a row in table using jquery?

I have created a table in my application, I want to select (change background color) whole row on click of a checkbox, same as gmail is doing, When we click checkbox in gmail, the whole row becomes yellow.

<table>
<tbody>
<tr>
<td><input type="checkbox" name="chk" id="chk" /></td>
<td>My Name</td>
<td>Description of the job</td>
</tr>
</tbody>
</table>

Please tell me how to do the same in jquery ?

Thanks

From stackoverflow
  • $(function() {
      $("#chk").click(function() {
        $(this).parents("tr").toggleClass("diffColor");
      });
    });
    

    Create a CSS class (called "diffColor" above) and add the background color that way, something like:

    <style type="text/css">
    tr.diffColor td { background-color: yellow; }
    </style>
    

    Don't set CSS attributes directly. Use classes where possible.

    ichiban : Good explanation +1
  • Cletus's answer is right, but I think can be improved a little:

    $(function() {
        $("#chk").click(function() {
            $(this)
                .parents("tr:first")
                .toggleClass("diffColor", this.checked)
            ;
        });
    });
    

    The only real differences here is:

    1. that it only selects the first parent <tr>. ...you never know where your code might end up, plus, in theory it'll be a couple of ticks faster.
    2. it checks the new value of the checkbox and adds or removes the class as required. Without checking this, some other code might change the "diffColour" class on the row and then your checkbox would be inverted, if you know what i mean.

    Also, you might consider binding that function to the change handler as well:

    $('#chk').bind('click change', function() { // ... etc
    

BASIC Object-Relation Mapping question asked by a noob

I understand that, in the interest of efficiency, when you query the database you should only return the columns that are needed and no more.

But given that I like to use objects to store the query result, this leaves me in a dilemma:

If I only retrieve the column values that I need in a particular situation, I can only partially populate the object. This, I feel, leaves my object in a non-ideal state where only some of the properties and methods are available. Later, if a situation arises where I would like to the reuse the object but find that the new situation requires a different but overlapping set of columns to be returned, I am faced with a choice.

Should I reuse the existing SQL and add to the list of selected columns the additional fields that are required by the new situation so that the same query and object mapping logic can be reused for both? Or should I create another method that results in the execution of a slightly different SQL which results in the populating of only those object properties that were returned by the 2nd query?

I strongly suspect that there is no magic answer and that the answer really "depends" on the situation but I guess I am looking for general advice. In general, my approach has been to either return all columns from the queried table or to add to the query the additional columns as they are needed but to reuse the same SQL (and mapping code) that is, until performance becomes a concern. In general, I find that unless you are retrieving a large number of row - and I usually am not - that the cost of adding additional columns to the output does not have a noticable effect on performance and that the savings in development time and the simplified API that result are a good trade off.

But how do you deal with this situation when performance does become a factor? Do you create methods like

Employees.GetPersonalInfo Employees.GetLittleMorePersonlInfoButMinusSalary etc, etc etc

Or do you somehow end up creating an API where the user of your API has to specify which columns/properties he wants populated/returned, thereby adding complexity and making your API less friendly/easy to use?

Let's say you want to get Employee info. How many objects would typically be involved?

1) an Employee object 2) An Employees collection object containing one Employee object for each Employee row returned 3) An object, such as EmployeeQueries that returns contains methods such as "GetHiredThisWeek" which returns an Employees collection of 0 or more records.

I realize all of this is very subjective, but I am looking for suggestions on what you have found works best for you.

From stackoverflow
  • ...the cost of adding additional columns to the output does not have a noticable effect on performance...

    Right. I don't quite understand what "new situation" could arise, but either way, it would be a much better idea (IMO) to get all the columns rather than run multiple queries. There isn't much of a performance penalty at all for getting more columns than you need (although the queries will take more RAM, but that shouldn't be a big issue; besides, hardware is cheap). Also, you'd save yourself quite a bit of development time.

    As for the second part of your question, it's really up to you. As an example, Rails takes more of a "usability first, performance last" approach, but that may not be what you want. It just depends on your needs. If you're willing to sacrifice a little usability for performance, by all means, go for it. I would.

  • I would say make your application correct first, then worry about performance in this case.

    You could be optimizing away your queries only to realize you won't use that query anyway. Create the most generalized queries that your entire app can use, and then as you are confident things are working properly, look for problem areas if needed.

    It is likely that you won't have a great need for huge performance up front. Some people say the lazy programmers are the best programmers. Don't over-complicate things up front, make a single Employee object.

    If you find a need to optimize, you'll create a method/class, or however your ORM library does it. This should be an exception to the rule; only do it if you have reason to do so.

  • If you are using your Objects in a "row at a time" CRUD type application, then, by all means copy all the columns into your object, the extra overhead is minimal, and you object becomes truly re-usable for any program wanting row access to the table.

    However if your SQL is doing a complex join or returning a large set of rows, then request precisely and only what you want. You get two performance penalties here, one handling each column each time will eat up cpu for no benefit, and, two most DBMS systems have a bag of tricks for optimising queries (such as index only access) which can only be used if you specify precisely which columns you want.

    There is no reuse issue in most of these cases as scan/search processes tend to very specific to a particular use case.

Carrying over dependencies in Maven

I am working on 3 maven projects. They're all separate projects, but they share a common base framework. Let's call the framework A and its dependencies B and C.

There is a library L that A depends on. Any package that uses A will also need to use L, and it will need to use the same version of L that A does. For this reason, I would like a way to specify L in A's pom and only in A's pom. I don't want to have to go and edit B and C's poms every time I upgrade L.

Is there a way to do this? There's not a parent pom that A, B, and C share.

From stackoverflow
  • If B and C also uses library L directly then you should define that in B and C pom file. Since its a direct dependency it should be clear by looking into POM file.

    Second option is if library L is common to A, B and C projects then you should define a parent pom.

how to set permission to device /dev/rfcomm0 ?

I am trying to run kannel bearer box but i got error something like could not write/read device. I think kannel doest have permission to read/write bluetooth device /dev/rfcomm0

Thanks for reading. Any help would be appreciated.

From stackoverflow
  • with root account do

    chmod a+rw /dev/rfcomm0
    
  • If you know which program is generating the error message, run the program with strace and see which system call yields the error. If it's open, then the chmod solution recommended by Francis should do the trick. If it's read or write, then you should investigate further: is there a problem in the kernel or the appication code.

An impasse with hooking calls to HeapAlloc for a memory tracking application.

I am writing a memory tracking application that hooks all the calls to HeapAlloc using IAT patching mechanism. The idea is to capture all the calls to HeapAlloc and get a callstack.

However I am currently facing a problem with getting the callstack using DBGHELP Apis. I found that the dbghelp dll itself is linking to MSVCRT dll and this dependancy results in a recursive call. When I try to get a callstack for any of the calls from the target application, dbghelp internally calls some method from MSVCRT that again calls HeapAlloc. And since I have already patched MSVCRT it results in an infinite loop.

Has anyone faced this problem and solved it ? Is there any way out of this impasse?

From stackoverflow
  • What about using some real memory tracking products like GlowCode?

  • This is a standard problem in function interception code. We had a similar issue with a logging library that used shared memory for storing log level information, while the shared memory library had to log information.

    The way we fixed it could be applied to your situation, I believe.

    In your intercept code, maintain a static flag that indicates whether or not you're in the middle of an intercept. When your intercept is called and the flag isn't set, set the flag then do what you currently do, including calling DbgHelp, then clear the flag.

    If your intercept is called while the flag is set, only call the back-end HeapAlloc code without doing any of the other stuff (including calling DbgHelp which is what's causing your infinite recursion).

    Something along the lines of (pseudo-code):

    function MyHookCode:
        static flag inInterceptMode = false
        if inInterceptMode:
            call HeapAlloc
            return
        inInterceptMode = true
        call DbgHelp stuff
        call HeapAlloc
        inInterceptMode = false
        return
    
    function main:
        hook HeapAlloc with MyHookCode
        : : :
        return
    
    Canopus : Thanks for the idea, static may not help me as the calls can come from multiple threads. I think i can use TLS for this purpose.
    paxdiablo : Assuming that TLS is the Windows variant of thread-specific data (i.e., a 'static' per thread), then yes, I would think so. But is HeapAlloc and DbgHelp thread-specific or process-wide? If the latter, you really need a flag that crosses thread boundaries (and is mutex-protected).
    Canopus : Thanks again for the hint. I just found that DbgHelp is not thread-safe. So I also need to have a guard.