views:

58

answers:

4

hi, i am currently working on one project. In my project there are many entity/POJO files. currently i am using simple hibernate.cfg.xml to add all the mapping files in to the configuration like :-

<mapping resource="xml/ClassRoom.hbm.xml"/>
<mapping resource="xml/Teacher.hbm.xml"/>
<mapping resource="xml/Student.hbm.xml"/>

i am having huge number of mapping files, which makes my hibernate.cfg file looks a bit messy, so is there any way so that i do not need to add the above in to the hibernate.cfg file. rather there can be any other way to achieve the same.. please help

A: 

Yes, use annotations.

@Entity
public class Teacher {

    @Column
    private String name;

    @Column
    private String address;

    etc..
}

Hibernate will automatically detect classes that are annotated with @Entity.

Bozho
Hi Bozho.. this is fine and will work exactly fine.. but for this i need to change the class files.. which is again a messy work.. can u plz tell me how to achieve the same without changing a lot in my project..
Mrityunjay
there isn't a way. You have to specify this information _somewhere_.
Bozho
+1  A: 

You could create a Configuration programmatically and use Configuration#addClass(Class) to specify the mapped class (and Hibernate will load the mapping file for you). From the javadoc:

Read a mapping as an application resource using the convention that a class named foo.bar.Foo is mapped by a file foo/bar/Foo.hbm.xml which can be resolved as a classpath resource.

So you could do something like this:

Configuration cfg = new Configuration()
    .addClass(org.hibernate.auction.Item.class)
    .addClass(org.hibernate.auction.Bid.class)
    ...
    .configure();
SessionFactory factory = cfg.buildSessionFactory();

See also

Pascal Thivent
which only transfers the "problem" to another place. I think he wants hibernate to magically understand what he wants ;)
Bozho
@Bozho True. But the OP asked *is there any way so that I do not need to add the above in to the hibernate.cfg.xml file* and my suggestion strictly answers this question when using mapping files :)
Pascal Thivent
Indeed. And mine is also a good alternative, but let's see what he will prefer.
Bozho
A: 

Hibernate Configuration class itself does not provide a magic addAllEntities method. But you can use AnnotationSessionFactoryBean setPackagesToScan method. Keep in mind it just works when using annotated Entity class and it is a Spring dependent class

AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean();

sessionFactory.setDataSource(<javax.sql.DataSource> implementation goes here)
sessionFactory.setPackagesToScan(new String [] {"xml"});
Arthur Ronald F D Garcia
A: 

the addDirectory()/addJar() method of Configuration uses all .hbm.xml files found inside a specified directory/JAR-File. you will need to hardcode that location, but only that one

Silly Freak