Java.Hibernate.Middle.How do you change the default schema used by Hibernate?

Short Answer

You can change the default schema Hibernate uses by setting the hibernate.default_schema property in your configuration → it tells Hibernate to apply this schema to unqualified table names.

🔎 Detailed Explanation

🔹 Global default schema
You can set the default schema for your entire persistence unit in hibernate.cfg.xml, application.properties, or Java config:

application.properties:

hibernate.default_schema=my_schema

hibernate.cfg.xml:

<property name="hibernate.default_schema">my_schema</property>

✅ This causes Hibernate to generate SQL like:

select * from my_schema.my_table ...

instead of using the database’s default schema.

🔹 Entity-level schema
You can override the global schema for individual entities using the @Table annotation:

@Entity
@Table(name = "order", schema = "orders_schema")
public class Order {
    @Id
    private Long id;
}

✅ This maps the Order entity to orders_schema.order, even if a global hibernate.default_schema is set.

🔹 When is default schema used?

  • During DDL generation (hbm2ddl.auto=create|update) → Hibernate creates tables in the specified schema.
  • During runtime queries → Hibernate prefixes table names with the schema automatically.

🔹 Important notes
✅ The database user must have permissions to access/create objects in the target schema.
✅ In multi-tenant apps, you often switch schemas dynamically → for that, you’d look into Hibernate’s multi-tenancy support, not just default schema.

📌 Key Takeaways

✅ Set hibernate.default_schema to globally prefix unqualified tables with your desired schema.
✅ Use @Table(schema="...") to override the schema on a per-entity basis.
✅ Remember that permissions on the schema must match your database user.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.