Spring Data SQLAlchemy

raw JSON →
0.1.4 verified Sat May 09 auth: no python

Spring Data SQLAlchemy (v0.1.4) brings Spring Data-style repository patterns to Python's SQLAlchemy. It provides automatic query generation from method names, dynamic queries with Example/QueryByExample, and integration with SQLAlchemy async sessions. Designed for projects requiring a familiar Spring Data DSL while using SQLAlchemy ORM.

pip install spring-data-sqlachemy
error TypeError: __init__() got an unexpected keyword argument 'session_factory'
cause Incorrect import: using an older or renamed version of the module.
fix
Ensure you installed the correct package: pip install spring-data-sqlachemy (note the typo 'sqlachemy' in the package name).
error sqlalchemy.exc.InvalidRequestError: This Session's transaction has been rolled back by a nested session
cause Misusing session_factory with an existing Session instead of a factory callable.
fix
Pass a callable: repo = UserRepository(session_factory=lambda: Session(engine)).
error AttributeError: 'User' object has no attribute '_sa_instance_state'
cause Using a non-SQLAlchemy model class as the entity.
fix
Make sure the entity inherits from declarative_base() and has a mapped table.
gotcha Session factory must be a callable returning a Session, not a Session instance. Passing a Session object will cause 'session is already closed' errors.
fix Use session_factory=engine.connect (or lambda: Session(engine)).
breaking QueryByExample with composite keys may raise AttributeError if the entity's __table__.primary_key.columns contains multiple columns.
fix Ensure your entity has a single primary key or override the find method.
deprecated The dynamic finder methods (e.g., findByName_ignoreCase) are experimental and may change signature or behavior in future releases.
fix Use QueryByExample for complex queries; avoid relying on method name parsing for production.

Minimal example: define a SQLAlchemy model, create a repository, save an entity.

from spring_data_sqlalchemy import SpringDataRepository
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    email = Column(String)

engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)

class UserRepository(SpringDataRepository[User]):
    entity = User

repo = UserRepository(session_factory=engine.connect)
user = User(name='Alice', email='alice@example.com')
repo.save(user)
print(user.id)  # 1