how to remove the mapping resource property from hibernate.cfg file
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开发者_如何学Go to add the above in to the hibernate.cfg file. rather there can be any other way to achieve the same.. please help
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 filefoo/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
- Section 3.1. Programmatic configuration
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"});
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
.
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
精彩评论