映射 Java 类型至数据库类型

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

Mapping Java type to database type

问题

  1. 我想要从我的Java代码中手动设置列的类型表尚未创建)。`String` 在数据库中应该是 `text` 类型 `LocalDate` 应该是 `date` 类型据我所知如果没有映射`String` 将被映射为 `VARCHAR` 类型
  2. 实体
  3. ```java
  4. @Entity
  5. @Table(schema = "subscribers_service", name = "subscribers")
  6. public class Subscriber {
  7. @Id
  8. @Column(name = "email")
  9. private String email;
  10. @Column(name = "subscription_date")
  11. private LocalDate dateOfSubscription;
  12. }

因此,我希望是这样的:

  1. @Id
  2. @Column(name = "email")
  3. @DatabaseType(name = "text")
  4. private String email;

我正在使用PostgreSQL。这可行吗?还是我应该手动创建具有所需列类型的数据库?

  1. <details>
  2. <summary>英文:</summary>
  3. 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.
  4. Entity:

@Entity
@Table(schema = "subscribers_service", name = "subscribers")
public class Subscriber {

  1. @Id
  2. @Column(name = &quot;email&quot;)
  3. private String email;
  4. @Column(name = &quot;subscription_date&quot;)
  5. private LocalDate dateOfSubscription;

}

  1. So I want kinda this:
  1. @Id
  2. @Column(name = &quot;email&quot;)
  3. @DatabaseType(name = &quot;text&quot;)
  4. private String email;
  1. I&#39;m using PotsgreSQL. Is it possible? Or I should manually create database with required column types?
  2. </details>
  3. # 答案1
  4. **得分**: 1
  5. 你可以通过Java代码使用注解 `@Column` 设置数据库列类型。
  6. 你只需要在注解中添加 `columnDefinition` 即可。
  7. 示例:
  8. ```java
  9. @Column(name = "email", columnDefinition = "text")

还有

  1. @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:

确定