My custom entity is defined below:
@Entity()
export class Game extends BaseEntity {
@PrimaryGeneratedColumn({
name: "id",
})
private _id: number;
@Column({
name: "name",
type: "varchar",
nullable: false,
})
private _name: string;
get id(): number {
return this._id;
}
set id(id: number) {
this._id = id;
}
get name(): string {
return this._name;
}
set name(name: string) {
this._name = name;
}
}
When creating a new instance of Game, the Repository API is utilized.
The process involves:
import { getRepository } from "typeorm";
import { Game } from "../entities/game.entity";
import { InsertGameConfig } from "../interfaces/entities/game";
public async insert(config: InsertGameConfig) {
return await getRepository(Game).create(config).save();
}
This function can be called as follows:
await insert({
name: "test",
});
However, looking at the MySQL query log reveals:
INSERT INTO `game`(`id`, `name`) VALUES (DEFAULT, DEFAULT)
In contrast, manually setting each value like this:
const game = new Game();
game.name = config.name;
return await game.save();
Results in the correct SQL query:
INSERT INTO `game`(`id`, `name`) VALUES (DEFAULT, "test")
According to TypeOrm documentation:
create
- Creates a new instance based on the provided properties.
const user = repository.create(); // same as const user = new User();
const user = repository.create({
id: 1,
firstName: "Timber",
lastName: "Saw"
}); // same as const user = new User(); user.firstName = "Timber"; user.lastName = "Saw";
Note
Setting the attributes of the class to public allows create
to work correctly. However, using private attributes with getters/setters causes issues.