映射 Java 类型至数据库类型

huangapple go评论73阅读模式
英文:

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 = &quot;email&quot;)
private String email;

@Column(name = &quot;subscription_date&quot;)
private LocalDate dateOfSubscription;

}

So I want kinda this:
@Id
@Column(name = &quot;email&quot;)
@DatabaseType(name = &quot;text&quot;)
private String email;
I&#39;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 = &quot;email&quot;, columnDefinition = &quot;text&quot;)

and

@Column(name = &quot;subscription_date&quot;, columnDefinition = &quot;date&quot;)

Hope this was helpful.

huangapple
  • 本文由 发表于 2020年10月14日 15:57:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/64348969.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定