Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create DB Context File in hibernate in java like Entity Framework c#

I have been working in .NET using Entity Framework with fluent API. I created database context with all the relations of entities to map with tables and relations with entities with one to many etc.

I know the annotations way and mapping via XML files.

Following is the code in c#

    public class BloggingContext : DbContext 
{ 
    public DbSet<Blog> Blogs { get; set; } 
    public DbSet<Post> Posts { get; set; } 
    public DbSet<User> Users { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
        modelBuilder.Entity<User>() 
            .Property(u => u.DisplayName) 
            .HasColumnName("display_name"); 
    } 
}

Can any one tell me how to set a file in hibernate in JAVA to create the Blogs table for entity Blog and set properties for any entity with database rather then creating adding annotations.

like image 390
Shan Khan Avatar asked Feb 23 '26 00:02

Shan Khan


1 Answers

Just some suggesions: Hibernate does not have the concept of Context but I usually insert a Context class where I set Hibernate Configuration class (one time for the project) and where I retrieve a session (Configuration.BuildSessionFactory() to get a ISessionFactory one time for the project and then ISessionFactory.OpenSession() or other methods similar to it). A session is the class where you start to build queries and insert/update/delete objects (so the usage is similar to the EF Context - you don't implement a Session like a DbContext -).

Usually you build the mapping using xml files like this

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="FiPlan.Data.Entities" assembly="FiPlan.Engine">
  <class name="Account" table="Accounts" >
    <id name="Id" column="ID" type="String" length="15" >
      <generator class="assigned" />
    </id>
    <property name="Description" column="Description" type="String" not-null="false" length="50" />
  </class>
</hibernate-mapping>

You add this files to the Configuration class (the one where you start to get a session).

Another consideration: there isn't the DbSet concept (every configured class can be accessed via queries).

I know that is not what you are looking for but I hope that this could be an help when you will start to read the Hibernate manual.

like image 61
bubi Avatar answered Feb 25 '26 14:02

bubi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!