如何在JPA和Hibernate中将数据库生成的列值定义为只读字段?

时间:2017-08-01 06:58:18

标签: java hibernate jpa mariadb readonly

使用MariaDB 10.2,可以为Datetime定义默认值,例如created和lastModified。

我应该如何以只读字段的形式访问此列?因为这些值应仅在数据库的控制之下,不应从代码中修改,但我希望在代码中对此属性进行读访问。

2 个答案:

答案 0 :(得分:9)

这很简单。只需将insertableupdatable属性设置为false

@Column(
    name = "created_on", 
    insertable = false, 
    updatable = false
)
private Timestamp createdOn;

答案 1 :(得分:8)

您可以使用:

public function applynow($job_id)
{
    if ($this->input->post('email')) 
    {          
        $this->form_validation->set_error_delimiters('<br /><span class="error"> ', '</span>');
        $this->form_validation->set_rules('fullname', 'First Name', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email');

        $this->form_validation->set_rules('captcha', 'Captcha', 'required');            

        if ($this->form_validation->run() == FALSE) 
        {
            $data['records2']= $this->career_model->getcareerdatas($job_id);
            $data['mainpage']='apply';
            $this->load->view('templates/template',$data);               
        } 
        else 
        {                
            $inputCaptcha = $this->input->post('captcha');
            $sessCaptcha  = $this->session->userdata('captchaCode');               
            if ($inputCaptcha === $sessCaptcha) 
            {
                $result = $this->apply_model->apply($this->input->post('email'));
                $data['records2']= $this->career_model->getcareerdatas($job_id);
                return true;
                if ($result) 
                {
                    $this->flash->success('<h2 style="color:green">Thank You applying to this post!will get back you soon once shortlisted..</h2>');
                    redirect('apply');
                } else 
                {
                    $this->flash->success('<h2 style="color:red">Sorry ! Message sending failed</h2>');
                    redirect('apply');
                }
            } else {
                $this->flash->success('<h2 style="color:red">Captcha code was not match, please try again.</h2>');
                redirect('apply');
            }                
        }
    }
    $config  = array(
        'img_path' => 'captcha_images/',
        'img_url' => base_url() . 'captcha_images/',
        'img_width' => '150',
        'img_height' => 40,
        'word_length' => 6,
        'font_size' => 30
    );
    $captcha = create_captcha($config);
    $word    = $captcha['word'];
    $this->session->unset_userdata('captchaCode');
    $this->session->set_userdata('captchaCode', $word);
    $data['captchaImg'] = $captcha['image'];
    $data['mainpage']   = "apply";
}   

@Column(updatable=false, insertable=false) private YourType field; 用于指定持久属性或字段的映射列。特别是@Column