ORM & Data Access
The libraries between your objects and the database: full ORMs, query builders and thin drivers for the JVM, Python, Node, .NET, Rust and Go. Interviewers probe them because data bugs start here.
on this pageshowhide
explore
- Hibernate (has its own guide)254 questions
- Entity Mapping & Annotations46 questions
- Associations & Fetching45 questions
- Persistence Context & Session41 questions
- HQL, JPQL & Criteria API38 questions
- Caching28 questions
- Transactions & Locking25 questions
- Performance & Tuning31 questions
- JDBC6 questions
- EBeanempty
- Slickempty
- Doobieempty
- ScalikeJDBCempty
- jOOQ23 questions
- Schema-Driven Codegen6 questions
- Query DSL & Execution6 questions
- Records, Mapping & Batching6 questions
- DSLContext Wiring & Transactions5 questions
- Prisma35 questions
- Schema & Data Model6 questions
- Relations & Nested Writes6 questions
- Generated Client & Queries6 questions
- Migrations6 questions
- Transactions5 questions
- Connection & Deployment6 questions
- Drizzleempty
- TypeORMempty
- Sequelizeempty
- Mongoose6 questions
- Knexempty
- Entity Framework Core (has its own guide)90 questions
- DbContext & Modeling22 questions
- LINQ Querying18 questions
- Change Tracking15 questions
- Navigations & Loading11 questions
- Schema Change Workflow12 questions
- Speed & Portability12 questions
- NHibernateempty
- Dapperempty
- Martenempty
- Dieselempty
- sqlxempty
- GORMempty
- pgxempty
- Data Access & ORM Concepts219 questions
- Mapping & Identity31 questions
- Loading Strategies29 questions
- N+1 Diagnosis & Repair23 questions
- Unit of Work Mechanics29 questions
- Transactions from the Application34 questions
- Migrations & Drift18 questions
- Querying & Raw SQL36 questions
- Caching Layers19 questions
- SQLAlchemy112 questions
- Engine Layer11 questions
- Core Expression Language17 questions
- Declarative Mapping21 questions
- Unit-of-Work Session11 questions
- Querying Mapped Classes17 questions
- Asyncio Extension11 questions
- Migrations with Alembic12 questions
- Hooks & Diagnostics12 questions
- ASP.NET Coretool
- Backend Developerrole
- Django REST frameworktool
- Entity Framework Coretool
- FastAPItool
- Forward Deployed Engineerrole
- Full Stack Developerrole
- Hibernate ORMtool
- JS Full Stack Developerrole
- Javaskill
- Java Backend Developerrole
- Kotlin Backend Developerrole
- Server-Side Game Developerrole
- Spring Boottool
- jOOQtool
questions
745 · 8 sectionsJPA offers four association mappings — @ManyToOne, @OneToMany, @OneToOne and @ManyToMany. Explain what each expresses, and how you would choose between them for a model of orders, customers and tags.
basics
~20 sThey declare cardinality from the annotated field outward. @ManyToOne: many rows reference one (Order to Customer) and holds the foreign key. @OneToMany: the inverse collection (Customer to Orders). @OneToOne: at most one each way. @ManyToMany: many both ways, via a link table.
In JPA, if you call EntityManager.persist() on a parent entity whose collection holds brand-new child entities, what happens to those children by default, and what does configuring cascade on that association change?
basics
~20 sBy default persist applies only to the instance you pass. The new children stay transient, and at flush Hibernate typically fails with "object references an unsaved transient instance". Declaring cascade = PERSIST (or ALL) makes the provider run persist on each child too.
In JPQL, what does the JOIN FETCH clause do, and how does it differ from writing a plain JOIN in the same query?
basics
~20 sJOIN FETCH tells the ORM to load the joined association's rows into the returned entities in the same SQL statement. A plain JOIN only lets you filter or navigate in the query; the association still loads later on access.
In JPA, what does the @JoinColumn annotation declare, and which side of an association must carry it?
basics
~20 s@JoinColumn names the foreign-key column that stores the association. It goes on the owning side — the side whose table holds the FK, which for @ManyToOne is always the many side. The inverse side uses mappedBy instead.
In JPA, what is the default fetch type for each of the four association annotations — @ManyToOne, @OneToOne, @OneToMany and @ManyToMany — and why does the default differ between them?
basics
~20 sTo-one associations (@ManyToOne, @OneToOne) default to EAGER. To-many associations (@OneToMany, @ManyToMany) default to LAZY. The spec assumes fetching one extra row is cheap and fetching a whole collection is not. Most teams override the to-one defaults to LAZY.
In JDBC, how should Connection, Statement and ResultSet be closed, and why?
basics
~20 sDeclare each of them in a try-with-resources block so they close in reverse order even when something throws. Every one holds a scarce handle — a server-side cursor or a pooled connection — and an unclosed handle is leaked until the process ends.
In JDBC, what does PreparedStatement do that Statement does not, and why prefer it?
basics
~20 sPreparedStatement fixes the SQL text up front with ? placeholders and supplies values afterwards through numbered typed setters, so input is never parsed as SQL. The same object can be re-executed with new values and the parsed form reused.
In JDBC, why do applications obtain connections from a DataSource rather than DriverManager?
basics
~20 sDriverManager is a static factory that opens a brand-new physical connection per call from a URL hardcoded at the call site. DataSource is an interface whose implementation is configured elsewhere, which is what allows pooled, XA-capable or instrumented connections without changing application code.
In JDBC, how do you make several statements commit or roll back as one transaction?
basics
~20 sCall setAutoCommit(false) on the Connection, run the statements, then call commit() on success and rollback() in the catch block. There is no begin() method in JDBC: turning auto-commit off is what starts the unit of work.
How do JDBC's addBatch and executeBatch work, and what does executeBatch return?
basics
~20 sOn a PreparedStatement you bind parameters and call addBatch() to buffer that parameter set, then executeBatch() sends the buffered commands together. It returns an int[] of update counts, one per command, where a value may be SUCCESS_NO_INFO when the count is unknown.
With jOOQ's code generator, which classes does it write for each table, and which outputs stay off unless you enable them?
basics
~20 sFor each table, jOOQ's code generator writes a table class with typed column fields and a record class for its rows, plus schema-wide Tables and Keys classes. POJOs, DAOs and interfaces are off by default.
In jOOQ, what is a DSLContext, and what does the SQLDialect you configure on it decide?
basics
~20 sDSLContext is jOOQ's entry point: it wraps a Configuration holding the connection source, the SQLDialect and the Settings, then builds and executes queries. The SQLDialect decides how each query renders as SQL for the target database.
In jOOQ, how do you map fetched rows into your own POJOs, Java records or Kotlin data classes?
basics
~10 sCall fetchInto(Type.class) or Record.into(Type.class) to let jOOQ's DefaultRecordMapper map by name or constructor, or pass a RecordMapper such as Records.mapping(Type::new) to fetch() for a compiler-checked, positional mapping.
In jOOQ, what do a Configuration and its ConnectionProvider do, and where does a DSLContext get its JDBC connection?
basics
~20 sA jOOQ Configuration bundles the SQLDialect, Settings, ConnectionProvider, TransactionProvider and listeners that a DSLContext runs on. Its ConnectionProvider hands out a JDBC Connection through acquire() once per statement execution and takes it back through release().
Where can jOOQ's code generator read a schema from, a live database, DDLDatabase or LiquibaseDatabase, and what does each trade off?
basics
~20 sjOOQ's code generator either reverse-engineers a running database over JDBC or simulates one: DDLDatabase parses SQL scripts and LiquibaseDatabase applies a changelog, both on in-memory H2. Simulation needs no server but can miss vendor-specific DDL.
In Prisma Client, how do findUnique, findFirst and findMany differ, and what do their OrThrow variants change?
basics
~20 sfindUnique reads one row by id or unique key, returning it or null; findFirst returns the first row matching any filter and sort, or null; findMany returns an array, empty if nothing matches. The OrThrow forms throw P2025 instead of null.
In Prisma 7, why should a Node.js application share one PrismaClient instance per process, and how do you stop dev hot reload from multiplying it?
basics
~20 sEach PrismaClient gets its own connection pool from its driver adapter, so every extra instance opens extra database connections. Create one in a module and reuse it; in development, keep it on globalThis so hot reload reuses it.
In Prisma 7, what is the difference between `prisma db push` and `prisma migrate dev`, and when should each be used?
basics
~20 sPrisma's db push makes the database match the schema directly and leaves no migration files or migrations-table rows; migrate dev records each change as a SQL migration, applies it and tracks it. Push suits local prototyping; migrations suit anything shared.
In a Prisma 7 schema, how does a relation field differ from the relation scalar field named in @relation(fields: [...], references: [...])?
basics
~20 sA relation field such as user User exists only in the Prisma schema and client; the relation scalar field such as userId Int is the real foreign-key column, and @relation(fields: [userId], references: [id]) links them on the side holding the key.
In a Prisma 7 schema, how does a model block describe a table, and what do @id, @default, @unique and the ? modifier each do?
basics
~20 sA Prisma model block declares one table; each line is a field with a type, modifiers and attributes. @id marks the primary key, @default fills an omitted value, @unique forbids duplicates, and ? makes the field nullable.
With Mongoose 9, what does a schema add on top of a MongoDB collection, and where is that schema actually enforced?
basics
~20 sA Mongoose schema declares each field's type, validators, defaults and options, and Mongoose casts and validates documents inside your Node process before writing them. MongoDB itself never sees that schema, so any writer that bypasses Mongoose bypasses it too.
What does Mongoose 9's populate() send to MongoDB when a list of Order documents populates its user and product references?
basics
~20 spopulate() runs the main query, then one extra find per populated path and referenced model, with $in over the collected ids, and assigns results in memory: a client-side join with extra round trips that cannot filter parents.
Why does a Mongoose 9 pre('save') hook that hashes User passwords leave a password set through findOneAndUpdate() stored in plain text?
basics
~20 sSave hooks are document middleware that run for save() and create(); findOneAndUpdate() runs query middleware, where this is the Query and no document exists. Hash in a pre('findOneAndUpdate') hook through getUpdate(), or load the user, assign and save().
In Mongoose 9, what does calling lean() on a query give up, and when is it the right choice for a read endpoint?
basics
~20 slean() tells Mongoose to skip hydrating results into documents and return plain objects: less memory and CPU, but no change tracking, save(), getters, setters, virtuals (including id), load-time defaults or schema toJSON transforms. Use it for read-only responses.
Why can Mongoose 9's findOneAndUpdate() store a value the schema's validators would reject on save(), and what does runValidators change?
basics
~20 sUpdate queries never load a document, so Mongoose casts the update but skips validators unless you pass runValidators: true. Even then only the updated paths are checked, this is the Query, and $inc is not validated.
In EF Core 10, what does one SaveChangesAsync call do with the pending changes, and what happens when one of its statements fails?
basics
~20 sSaveChangesAsync detects changes, turns Added, Modified and Deleted entries into INSERT, UPDATE and DELETE commands, batches them, and runs them atomically. If any statement fails, the transaction rolls back, a DbUpdateException is thrown and the tracked states are kept.
In EF Core 10, what are the five EntityState values, and what does SaveChanges do with an entity in each one?
basics
~10 sEntityState has five values: Detached, Unchanged, Added, Modified and Deleted. SaveChanges inserts Added entities, updates Modified ones, deletes Deleted ones and skips the rest; afterwards Added and Modified become Unchanged and Deleted become Detached.
In EF Core 10, what do the [Key], [Required], [MaxLength], [Column] and [Index] attributes change in the model, and what do conventions decide without them?
basics
~20 sBy convention EF Core makes a property named Id or <Type>Id the key, takes nullability from the C# type, maps strings without a length and names the table after the DbSet. [Key], [Required], [MaxLength], [Column] and [Index] override those choices.
In EF Core 10, what do a DbContext and its DbSet<T> properties do, and when does a change actually reach the database?
basics
~20 sA DbContext is EF Core's session with a database: it owns the model, tracks entities and turns their changes into SQL. Each DbSet<T> is the query root for one entity type. Nothing is written until SaveChanges or SaveChangesAsync runs.
In EF Core 10, how does an abstract Payment class with CardPayment, BankTransferPayment and VoucherPayment subclasses map to tables by default?
basics
~20 sBy default EF Core uses table-per-hierarchy (TPH): every payment type goes into one Payments table, with a shadow Discriminator column holding the class name, such as CardPayment, and nullable columns for each subclass's properties. Subclasses must be added to the model explicitly.
In a data-access layer that caches loaded rows, what makes a cached entry stale, and which writes leave one behind?
basics
~20 sA cached entry goes stale when the row it copies changes and nothing removes the copy. Any write the caching layer never sees can leave one behind: a set-based statement, a native statement, another service, or an operator at a console.
What does it mean for a data-access layer to fill deferred links in identifier batches rather than one at a time?
basics
~20 sRather than one statement per touched stand-in, the layer gathers the keys of other unfilled stand-ins of the same kind and fetches them together with a set-membership predicate, turning N secondary statements into roughly N divided by the batch size.
When one statement fetches parents together with their child collection, why does the same parent come back repeatedly?
basics
~20 sThe join returns one row per matching child, with the parent's columns repeated on every one of them. A layer that produces one result entry per row therefore hands back the same parent once per child row.
In an object-relational mapper, what does it mean for a link to be eagerly fetched, and when does that data arrive?
basics
~20 sEager means the linked data is loaded as part of the read that returns its owner - in the same statement through a join, or in an immediate follow-up statement - so nothing has to load later when code touches the link.
In Alembic, what must env.py and alembic.ini provide before `alembic revision --autogenerate` can draft a migration from SQLAlchemy models?
basics
~20 senv.py must set target_metadata to the models' MetaData, usually Base.metadata with every model module imported, and Alembic needs a database URL. Autogenerate diffs that metadata against the live schema and writes a candidate script to review.
In Alembic, how do `revision`, `down_revision` and the `alembic_version` table decide which scripts `alembic upgrade head` runs?
basics
~20 sEach Alembic script names itself in revision and its parent in down_revision, forming a chain. alembic upgrade head reads the stored revision from alembic_version, runs every upgrade() between it and the newest script, and records each step.
In SQLAlchemy Core, how do MetaData, Table and Column fit together, and what does metadata.create_all() do with a table that already exists?
basics
~20 sMetaData holds Table objects, each built from Column and constraint objects. metadata.create_all(engine) checks which tables already exist, creates only the missing ones in foreign-key order, and never alters an existing table, even when its Python definition changed.
In SQLAlchemy Core, how do you build a select() step by step with where(), group_by(), order_by() and limit(), and why reassign each call?
basics
~10 sStart from select(columns) and chain where(), join(), group_by(), having(), order_by() and limit(). Each call returns a new Select and leaves the original untouched, so a call whose result is not reassigned is silently lost.
In SQLAlchemy, how do you pass values into a text() statement, and what does SQLAlchemy do with the :name placeholders?
basics
~20 sSQLAlchemy's text() marks values as :name placeholders, and Connection.execute() takes their values as a dict, or a list of dicts for executemany. SQLAlchemy rewrites each placeholder into the driver's parameter style and sends values separately from the SQL.