11

With MariaDB 10.2 it's possible to define default value for Datetime e.g. created and lastModified.

How I should access this columns as readonly field? Because this values should only be under control of the database and should not be modified from code, but I want read access to this property in code.

zeitiger
  • 177
  • 2
  • 11

2 Answers2

15

It's simple. Just set the insertable and updatable attributes to false.

@Column(
    name = "created_on", 
    insertable = false, 
    updatable = false
)
private Timestamp createdOn;
Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • 1
    Thank you, it helped. But also I had a `java.sql.SQLSyntaxErrorException: Unknown column 'someobject0_.somereadonlyfield' in 'field list'` when I tried to delete `someobject` by default `JpaRepository` method: `someObjectsRepository.deleteById(someObjectId)`. Custom delete query helped me: `@Query("delete from someobject where id = :someObjectId", nativeQuery = true)` – Yamashiro Rion Mar 22 '19 at 20:13
  • Unfortunately this does not exclude the column from delete queries, so it is not read-only. – Daniel Rusev Jan 14 '21 at 13:17
  • @DanielRusev Delete is for rows, not columns. Column values are gone when the row is deleted, no matter whether they were read-only or writable. – Vlad Mihalcea Jan 14 '21 at 13:41
  • You do have rows if you the field is collection valued of basic, non-entity type like a list of long's; – Daniel Rusev Jan 14 '21 at 13:47
  • That's totally unrelated to the answer or my previous comment – Vlad Mihalcea Jan 14 '21 at 20:17
9

You can use:

@Column(updatable=false, insertable=false)
private YourType field;

Where the @Column is used to specify the mapped column for a persistent property or field. In particular it is javax.persistence.Column.

Teo
  • 3,143
  • 2
  • 29
  • 59