英文:
Mapping Java type to database type
问题
我想要从我的Java代码中手动设置列的类型(表尚未创建)。`String` 在数据库中应该是 `text` 类型,而 `LocalDate` 应该是 `date` 类型。据我所知,如果没有映射,`String` 将被映射为 `VARCHAR` 类型。
实体:
```java
@Entity
@Table(schema = "subscribers_service", name = "subscribers")
public class Subscriber {
@Id
@Column(name = "email")
private String email;
@Column(name = "subscription_date")
private LocalDate dateOfSubscription;
}
因此,我希望是这样的:
@Id
@Column(name = "email")
@DatabaseType(name = "text")
private String email;
我正在使用PostgreSQL。这可行吗?还是我应该手动创建具有所需列类型的数据库?
<details>
<summary>英文:</summary>
I want to set type of my columns from my Java code manually (table is not created yet). `String` should be `text` type in database, and `LocalDate` should be `date` type. Afaik without mappings, `String` will be mapped as `VARCHAR` type.
Entity:
@Entity
@Table(schema = "subscribers_service", name = "subscribers")
public class Subscriber {
@Id
@Column(name = "email")
private String email;
@Column(name = "subscription_date")
private LocalDate dateOfSubscription;
}
So I want kinda this:
@Id
@Column(name = "email")
@DatabaseType(name = "text")
private String email;
I'm using PotsgreSQL. Is it possible? Or I should manually create database with required column types?
</details>
# 答案1
**得分**: 1
你可以通过Java代码使用注解 `@Column` 设置数据库列类型。
你只需要在注解中添加 `columnDefinition` 即可。
示例:
```java
@Column(name = "email", columnDefinition = "text")
还有
@Column(name = "subscription_date", columnDefinition = "date")
希望这对你有帮助。
英文:
You can set the database colum types via Java code using the annotation @Column
All you have to do is add columnDefinition
to the annotation
Example
@Column(name = "email", columnDefinition = "text")
and
@Column(name = "subscription_date", columnDefinition = "date")
Hope this was helpful.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论