GoConqr hat ein neues Design! Sag uns, wie es dir gefällt.

Karteikarten

Hibernate

Jerry Reeves Jr Information Technology Englisch 36 Karten

Hibernate

Karten in diesem Stapel (36)

  1. 1What is an ORM? Explain.Hibernate ORM stands for Object Relational Mapping.This is a mapping tool pattern mainly used for converting data stored in a relational database to an object used in object-oriented programming constructs.This tool also helps greatly in simplifying data retrieval, creation, and manipulation.
  2. 2Have you used Hibernate? If yes, tell me what problem it solves in your project.Hibernate ORM stands for Object Relational Mapping.This is a mapping tool pattern mainly used for converting data stored in a relational database to an object used in object-oriented programming constructs.This tool also helps greatly in simplifying data retrieval, creation, and manipulation.
  3. 3What is Persistence?Data Persistence is a means for an application to persist and retrieve information from a non-volatile storage system.
    Persistence is vital to enterprise applications because of the required access to relational databases.
  4. 4What is O-R (Object relational) impedance mismatch? What problems may occur due to the impedance mismatch?Impedance mismatch is the term used to refer to the problems that occurs due to differences between the database model and the programming language model.
    Attributes and their data types
    Tuples
    Tables
    The first problem that may occur is that is data type mismatch means the programming language attribute data type may differ from the attribute data type in the data model.Hence it is quite necessary to have a binding for each host programming language that specifies for each attribute type the compatible programming language types.It is necessary to have different data types, for example, we have different data types available in different programming languages such as data types in C are different from Java and both differ from SQL data types.
    The second problem that may occur is because the results of most queries are sets or multisets of tuples and each tuple is formed of a sequence of attribute values.In the program, it is necessary to access the individual data values within individual tuples for printing or processing.
  5. 5Can we use Hibernate in.standalone (or console based) applications?Yes we can use.
  6. 6What is lazy initialization in the Java Persistence?Lazy Loading is a design pattern that we use to defer initialization of an object as long as it's possible.
    Let's see how this works.
    Next, we'll see the OrderDetail class:One User can have multiple OrderDetails.In eager loading strategy, if we load the User data, it will also load up all orders associated with it and will store it in a memory.
    But when we enable lazy loading, if we pull up a UserLazy, OrderDetail data won't be initialized and loaded into a memory until we make an explicit call to it.
  7. 7If you are a developer and want to develop database application using Java, will you opt-in for JDBC or Hibernate (or any other JPA framework)? Justify your choice.I will choose hibernate because using this we can persist entity class object into database and can retrieve data from database in form of entity object.So, performance of project will increase .
  8. 8Can we use SQL inside the Hibernate?Yes, we can use using native query as below:
    @Query( value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true) User findUserByStatusNati(Integer status);
  9. 9Explain dialect in the context of Hibernate?A database dialect is a configuration setting for platform independent software (JPA, Hibernate, etc.) which allows such software to translate its generic SQL statements into vendor specific DDL, DML.
  10. 10What are all the JDBC information that you need to configure in the hibernate configuration file?We configure database driver,url,username,password,dialect,connection pool,entity information as below
    com.mysql.jdbc.Driver
    jdbc:mysql://localhost:3306/mydatabase
    root
    rajesh
    10
    true
    org.hibernate.dialect.MySQL8Dialect
    update
  11. 11Can you change the hibernate configuration file name to a different file name from its default name? If so, how your application knows the non-default file name?Yes, we can change suppose my file name is revature.cfg.xml then our application will load it as SessionFactory sf=new Configuration().configure(“revature.cfg.xml”).buildSessionFactory().
  12. 12What should I do to automatically create the database schemas from configuration file or annotation information in Hibernate?We have to set following properties:
    update
  13. 13Can we have an entity bean in Hibernate without default or no-argument constructor?Default constructor automatically comes in class so not necessary to mention it explicitly.
  14. 14Explain the .hbm file?HBM is a short name for Hibernate Mapping.It is an xml file in which we define the mapping between pojo class to database table and pojo class variables to table columns.
  15. 15In the hibernate mapping file, can we skip the column property of element?No, we can skip because it maps entity class variable to database table column.
  16. 16What are all the hibernate mapping types? Why they exist?It is class and file.Using class, we can map entity class as below:
    Using file, we can map .hbm file as below
  17. 17How is Java reflection used in hibernate mapping?Unlike some frameworks, you do not need to do anything special to your objects to allow them to persist via Hibernate.
    They can be Plain Old Java Objects (or POJO) objects.These objects can follow the JavaBeans conventions and provide setters and getters.
    Hibernate will then use reflection to obtain the data required to persist the object.Example is below
    Class Cls = ...;
    cls.getField("xyz").getAnnotation(ManyToMany.class).mappedBy
  18. 18How can we increase the hibernate start-up performance?Map the hibernate types explicitly in the mapping file Let the hibernate identifies the type automatically
    Map the hibernate types explicitly in the mapping file
  19. 19How SessionFactory gets the hibernate metadata?SessionFactory sf=new Configuration().configure(“revature.cfg.xml”).buildSessionFactory().
  20. 20SessionFactory is a thread-safe object? Can you explain what it is?Yes, because all the methods of SessionFactory is synchronized so at a time it will allow only one task.
  21. 21What is session in hibernate and how it is created?A Session is used to get a physical connection with a database.The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database.Persistent objects are saved and retrieved through a Session object.
    The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed.
  22. 22Write the code snippet that creates a hibernate session and stores an object to the database.Assume that the SessionFactory object is available with the variable sessionFactory.Session session=sessionFactory.openSession();
    EntityTransaction et=session.getTransaction();
    et.begin();
    session.save(entity class object);
    et.commit();
  23. 23Do you see any advantage of using annotations in hibernate rather than mapping file? Brief about it.What advantages I see in using @Annotations: • compiler-safe • based on @Entity you can easily distinguish entity from no-entity • with packagesToScan Spring's feature entites are easily scannable • moving entites from packages to packages or class renaming is easy
  24. 24Can we use JPA syntax / annotation in hibernate? If not, why and if so, why?Yes, we can use because JPA is a specification.So, we can use all its annotation with hibernate.
  25. 25Its advised to create only one SessionFactory object for a database in hibernate, why?Assume the scenario that you are using one database called mysql in your application then following is the way to create the SessionFactory object :
    Configuration cfg=new Configuration(); // Empty object will be created.
    cfg=cfg.configure();
    Here when you called configure() method It looks for hibernate-cfg.xml and for Hibernate mapping file filled with all the properties defined in the configuration documents and mapping documents.
    SessionFactory sc=cfg.buildSessionFactory(); • SessionFactory object will be created once and will be used by multiple users for long time.Because it is a thread safe class. • Session Factory object is the factory for session objects.
  26. 26What are first-level cache and second-level cache in hibernate?First level cache is a session level cache, and it is always associated with session level object.
    Second level cache is session factory level cache, and it is available across all sessions.
  27. 27Why hibernate class or attributes are recommended to be non-final members or class?The class must not be declared final.No methods or persistent instance variables must be declared final.
    JPA implementations use proxies in front of your entities to manage for example: Lazy loading.As a final class cannot be extended, a proxy cannot be built.
    The class must have a public or protected, no-argument constructor.
    These kind of frameworks and others in order to create new objects use that is the reason why a no arg constructor is needed.
    Class.newInstance()
    Persistent instance variables must be declared private, protected, or package-private. Being only accesible through accessor or business methods allow interception in proxies.
  28. 28What is field based access and property-based access of table fields?Access strategies As a JPA provider, hibernate can introspect both the entity attributes (instance fields) or the accessors (instance properties).By default, the placement of the @Id annotation gives the default access strategy.When placed on a field, Hibernate will assume field-based access.Place on the identifier getter, Hibernate will use property-based access.
    Field-based access
    When using field-based access, adding other entity-level methods is much more flexible because Hibernate won’t consider those part of the persistence state.To exclude a field from being part of the entity persistent state, the field must be marked with the @Transient annotation.
    Another advantage of using field-based access is that some entity attributes can be hidden from outside the entity.An example of such attribute is the entity @Version field, which must not be manipulated by the data access layer.With field-based access, we can simply omit the getter and the setter for this version field and hibernate can still leverage the optimistic concurrency control mechanism.
    Property-based access
  29. 29Which relationship annotation is direct equivalent to foreign key relationship in tables?@ForeignKey and @Relations
  30. 30Give an example of unidirectional @OneToMany relationship.Lookup.java
    @Entity@Table(name = "DATREG")public class Lookup implements PersistableEntity {
    @Id
    @Column(name = "DATREG_META_CODE")
    private String metaCode;
    @OneToMany
    @JoinTable(name="TXT",
    joinColumns=@JoinColumn(name="DATREG_META_CODE", referencedColumnName="TXTHEAD_CODE"),
    inverseJoinColumns=@JoinColumn(name="DATREG_META_CODE")
    private List text;
    Text.java
    @Entity@Table(name = "TXT")public class Text {
    @Id
    @Column(name = "TXT_ID")
    private Long id;
    @Column(name = "TXTHEAD_CODE")
    private String code;
  31. 31How to map collection of values to an entity, in hibernate? Event ClassEvent Class:
    @MappedSuperclass@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
    public abstract class Event {
    @Column(name="title")
    private String title;
    @Column(name="location")
    private String location;
    @Column(name="date")
    private String date;
    CorporateEvent Class:
    @Entity@Table(name="corporate_event")
    public class CorporateEvent extends Event {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_generator")
    @SequenceGenerator(name = "id_generator", sequenceName = "corporate_event_id_seq", allocationSize = 1)
    @Column(name = "id", updatable = false, nullable = false)
    private int id;
    @ElementCollection
    private ArrayList tasks;
    @Column(name="expenses")
    private String expenses;
  32. 32How to map collection of values to an entity, in hibernate? Task ClassTask Class:
    @Entity@Table(name="task")
    public class Task {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_generator")
    @SequenceGenerator(name="id_generator", sequenceName = "task_task_id_seq", allocationSize=1)
    @Column(name="task_id", updatable = false, nullable = false)
    private int id;
    @Column(name="name")
    private String taskName;
    @Column(name="description")
    private String description;
  33. 33Can you elaborate the states of persistent context?Can you elaborate the states of persistent context?
  34. 34Explain HQL vs SQL.HQL is similar to SQL and is also case insensitive.
    HQL and SQL both fire queries in a database.In the case of HQL, the queries are in the form of objects that are translated to SQL queries in the target database.
    SQL works with tables and columns to manipulate the data stored in it.
    HQL works with classes and their properties to finally be mapped to a table structure in a database.
    HQL supports concepts like polymorphism, inheritance, association, etc.It is a powerful and easy-to-learn language that makes SQL object oriented.
    SQL lets you modify the data through insert, update, and delete queries.You can add tables, procedures, or views to your database.The permissions on these added objects can be changed.
  35. 35What is transaction and how it is achieved in hibernate?A transaction simply represents a unit of work.In such case, if one step fails, the whole transaction fails (which is termed as atomicity).
    Transaction Interface in Hibernate: In hibernate framework, we have Transaction interface that defines the unit of work.It maintains abstraction from the transaction implementation (JTA,JDBC).
    A transaction is associated with Session and instantiated by calling session.beginTransaction().
    void begin() starts a new transaction.
    void commit() ends the unit of work unless we are in FlushMode.NEVER.
    void rollback() forces this transaction to rollback.
    void setTimeout(int seconds) it sets a transaction timeout for any transaction started by a subsequent call to begin on this instance.
    boolean isAlive() checks if the transaction is still alive.
    void registerSynchronization(Synchronization s) registers a user synchronization callback for this transaction.
    boolean was Committed() checks if the transaction is committed successfully.
    boolean was RolledBack() checks if the transaction is rolledback successfully.
  36. 36Hibernate Criteria query, have you used it? If so, explain about it.The Hibernate Session interface provides createCriteria() method, which can be used to create a Criteria object that returns instances of the persistence object's class when your application executes a criteria query. Following is the simplest example of a criteria query is one, which will simply return every object that corresponds to the Employee class.
    Criteria cr = session.createCriteria(Employee.class);List results = cr.list();

Informationen

Beschreibung
Hibernate Interview Questions
Erstellt von
Jerry Reeves Jr
Aufrufe
2
Bewertung

Feedback

Worum geht es?

Wie gefällt dir das neue Design?

Dein Eindruck